Search code examples
iosobjective-cuiimageviewuiimagecalayer

How do I mask a UIImageView without use of another UIImage, just simply defining a simple shape like a rounded-square?


Say I have an image of a picturesque landscape. A rectangle, say 300x200 in dimensions.

How would I go about masking a square of say, 200x200 of the image with rounded corners into a UIImageView I could then present to the user?

I see tons of examples such as this question where they go over how to use a UIImage as the mask, but I just need a simple shape (a rounded square).

How would I go about accomplishing a simple mask like this without a UIImage?


Solution

  • You can use a CAShapeLayer to mask your UIImageView. Code is as followings:

    UIBezierPath *maskPath;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 200, 200) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10.0, 10.0)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = CGRectMake(0, 0, 200, 200);
    maskLayer.path = maskPath.CGPath;
    
    self.imageView.layer.mask = maskLayer;