简体   繁体   中英

Draw line in Dynamically created UIView

I need to draw a shape/line in my dynamically created view. Here is the code I'm trying but it doesn't draw anything though the views are being added.

//loc1 and loc2 are the touch locations on the view used to draw a rect
UIView *vw = [[UIView alloc] initWithFrame:CGRectMake(loc1.x, loc1.y,loc2.x - loc1.x, loc2.y - loc1.y)];
UIGraphicsBeginImageContext(vw.bounds.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0/255.0, 0.0/255.0, 255.0/255.0, 1.0);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2);
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 50, 50));
CGContextStrokePath(UIGraphicsGetCurrentContext());
UIGraphicsEndImageContext();

[mainImageView addSubview:vw];

If you are going to add a divider/line on your view, you can use UIView as you did. With 1 or 2 px of width/height (depends on which orientation you ask for) and proper backgroundColor, you can create a divider of your own, and add it to your subview.

Not sure what exactly is your requirement. Try the below code

//loc1 and loc2 are the touch locations on the view used to draw a rect
[[UIView alloc] initWithFrame:CGRectMake(loc1.x, loc1.y,loc2.x - loc1.x, loc2.y - loc1.y)];

UIGraphicsBeginImageContext(vw.bounds.size);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0/255.0, 0.0/255.0, 255.0/255.0, 1.0);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2);
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 50, 50));
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGImageRef result = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
UIGraphicsEndImageContext();

UIImage *image = [UIImage imageWithCGImage:result];
CGRect imageFrame = CGRectZero;
imageFrame.origin = CGPointMake(0, 30); // Change according to your requirement
imageFrame.size = image.size;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame];
imageView.image = image;
[vw addSubview:imageView];

[self.view addSubview:vw];

I would subclass UIView and add your drawing code to drawRect:

- (void)drawRect:(CGRect)rect{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetRGBStrokeColor(ctx, 0.0/255.0, 0.0/255.0, 255.0/255.0, 1.0);
CGContextSetLineWidth(ctx, 2);
CGContextAddRect(ctx, CGRectMake(0, 0, 50, 50));
CGContextStrokePath(ctx);
}

And then add your custom UIView as subview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM