Question

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];
Was it helpful?

Solution 2

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];

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top