11

I am trying to mask an image so that I can give it only two rounded corners. With the code that I have it just adds the mask in white over the image, but doesn't seem to apply it. What do I need to do different to mask the image corners?

CAShapeLayer *maskLayer = [CAShapeLayer layer];
UIBezierPath *roundedPath = [UIBezierPath bezierPathWithRoundedRect:maskLayer.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(16.f, 16.f)];    
maskLayer.fillColor = [[UIColor whiteColor] CGColor];
maskLayer.backgroundColor = [[UIColor clearColor] CGColor];
maskLayer.path = [roundedPath CGPath];

// Add mask
self.imageView.layer.mask = maskLayer;
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

1 Answers1

7

Round two corners in UIView

As mentioned in the above linked question, you probably need to remove the view from the heirarchy before applying its mask.

[self.imageView removeFromSuperview];
self.imageView.layer.mask = maskLayer;
[self.view addSubview:self.imageView];

Also, your maskLayer has no bounds. You need to set it to the frame (or bounds) of the view you're trying to mask.

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.imageView.frame;
Community
  • 1
  • 1
  • 1
    Please read Apple's documentation. I would start with [`UIImage`](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html), and also [`CGImage`](http://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGImage/Reference/reference.html#//apple_ref/doc/uid/TP30000956-Reference-DontLinkElementID_1), which is the underlying image object inside a `UIImage`. You'll see that in `CGImage` there are functions to create an image using a mask, and then a `UIImage` constructor which takes your new `CGImage` as the image. –  Apr 30 '13 at 01:06