jean bernard
jean bernard

Reputation: 257

use a CALayer as a UIImageView

I would like to create a CALayer bezier path in a circle shape. And I would like to set it like it was a UIImageView (to be able to move it with animation etc.) Is it possible? If so how can I do it? Thank you.

Upvotes: 1

Views: 2426

Answers (2)

tarmes
tarmes

Reputation: 15442

You could always add a CAShapeLayer to your view. During init, do something like (all untested):

CAShapeLayer *circle = [[CAShapeLayer alloc] init];
[self.layer addSublayer:circle];

Then, in drawRect, layoutSubViews, or some other place that seems appropriate to update the layout:

circle.fillColor = [[UIColor redColor].CGColor;
CGMutablePathRef p = CGPathCreateMutable();
CGPathAddEllipseInRect(p, NULL, self.bounds);
circle.path = p;
circle.bounds = self.bounds;
circle.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

Upvotes: 2

jrturton
jrturton

Reputation: 119292

I'm not sure what you mean by a "CALayer bezier path" but you have a couple of options here:

  1. Create a subclass of UIView, where you draw your circle using UIBezierPath methods in the drawRect:. This view can then be added to another view as a subview and animated using standard methods. However, you are warned that this may affect performance, (as it has to keep re-drawing) so if that does turn out to be a problem...
  2. Create a graphics context and draw your circle in there. Take an image from this graphics context and set it as the image for a UIImageView. Animate as in answer (1). This way you aren't redrawing all the time so performance would be better, but try with option 1 first as it is simpler, and if you have simple drawing code it shouldn't affect you too much.

For option 2, you begin a graphics context using UIGraphicsBeginImageContextWithOptions - you then do your drawing, and extract the image using UIGraphicsGetImageFromCurrentImageContext, then end the context using UIGraphicsEndImageContext. Those functions are all documented here

Sample code to do this:

CGFloat radius = 50;
CGSize size = CGSizeMake(radius*2,radius*2);
CGPoint centre = CGPointMake(radius,radius);

UIGraphicsBeginImageContextWithOptions(size,NO, 0.0);
UIBezierPath * solidPath = [UIBezierPath bezierPathWithArcCenter:centre radius:edgeSize/20 startAngle:0 endAngle:2 * M_PI clockwise:YES];
[solidPath closePath];
[[UIColor whiteColor] set];
[solidPath fill];

UIImage *circle = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithImage:circle];

Upvotes: 1

Related Questions