0

I have a UIImageView that is basically a partially-opaque, blue oval. I allow the user to manually scale the height and width of the oval. After the oval's frame has been set to the desired size, I want to replace the blue oval with an image masked to the shape of the oval. How can I do this?

user1007895
  • 3,925
  • 11
  • 41
  • 63

2 Answers2

0

I use this piece of code:

#import <QuartzCore/QuartzCore.h>

CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage];
mask.frame = CGRectMake(0, 0, imgWidth, imgHeight);
maskedImageView.layer.mask = mask;
maskedImageView.layer.masksToBounds = YES;
Xithias
  • 991
  • 1
  • 14
  • 32
0

By the way, if the mask is really just an oval, rather than using an image to do the masking, you can also use a CAShapeLayer:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(x,y,w,h)];
shapeLayer.path = [path CGPath];
self.imageView.layer.mask = shapeLayer;

And, when you want to move/resize the mask, just create a new UIBezierPath and update the path property of this shapeLayer.

Rob
  • 415,655
  • 72
  • 787
  • 1,044