Drawing a shape in UIImageView iOS

I am trying to make some circles inside a UIImageView with a specific image. This is what I tried to do:

UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef contextRef = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(contextRef, 2.0); CGContextSetStrokeColorWithColor(contextRef, [color CGColor]); CGRect circlePoint = (CGRectMake(coordsFinal.x, coordsFinal.y, 50.0, 50.0)); CGContextStrokeEllipseInRect(contextRef, circlePoint); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [photoView addSubview:image]; 

The circle is drawn perfectly, but I would like the PhotoView to act as a mask for it. Therefore, if, for example, I move a UIImageView from a UIView using animation, I would like the circle to move with it. The important thing is that the coordinates apply to the entire screen.

+6
source share
1 answer

Instead, use the main animation form layer.

 CAShapeLayer *circleLayer = [CAShapeLayer layer]; // Give the layer the same bounds as your image view [circleLayer setBounds:CGRectMake(0.0f, 0.0f, [photoView bounds].size.width, [photoView bounds].size.height)]; // Position the circle anywhere you like, but this will center it // In the parent layer, which will be your image view root layer [circleLayer setPosition:CGPointMake([photoView bounds].size.width/2.0f, [photoView bounds].size.height/2.0f)]; // Create a circle path. UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(0.0f, 0.0f, 50.0f, 50.0f)]; // Set the path on the layer [circleLayer setPath:[path CGPath]]; // Set the stroke color [circleLayer setStrokeColor:[[UIColor redColor] CGColor]]; // Set the stroke line width [circleLayer setLineWidth:2.0f]; // Add the sublayer to the image view layer tree [[photoView layer] addSublayer:circleLayer]; 

Now, if you animate the UIImageView that contains this layer, the layer will move with it since it is a child. And now there is no need to override drawRect:

+10
source

All Articles