How to add a circular mask to a UIImageview and change the frame and centers while doing so?

akshaynhegde picture akshaynhegde · Mar 9, 2013 · Viewed 13.5k times · Source

I would like to add a circular mask to UIImageVIew. Here is the function that am using to add the mask..

- (void) addMaskToBounds:(CGRect) maskBounds
{
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    CGPathRef maskPath = CGPathCreateWithEllipseInRect(maskBounds, NULL);
    maskLayer.bounds = maskBounds;
    [maskLayer setPath:maskPath];
    [maskLayer setFillColor:[[UIColor blackColor] CGColor]];
    maskLayer.position = CGPointMake(maskBounds.size.width/2, maskBounds.size.height/2);

    [self.imageView.layer setMask:maskLayer];
}

Am able to add the mask but the problem occurs since am changing the image frame and center along with it. The image is enlarged and made small based on the user actions. Hence I would have to add the mask twice when small and when enlarged. So Since am animating the frame change, while animating the image become distorted, or displaced. How do I overcome this ?

I guess its best explained with an example project. Here I have created a Demo project https://github.com/akshaynhegde/MaskImage on GitHub, just run it to see my problem and let me know how resolve the problem.

Answer

Mrug picture Mrug · Jun 16, 2014

Hope this will help

    CAShapeLayer *circle = [CAShapeLayer layer];
    // Make a circular shape
    UIBezierPath *circularPath=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, _imgView.frame.size.width, _imgView.frame.size.height) cornerRadius:MAX(_imgView.frame.size.width, _imgView.frame.size.height)];

    circle.path = circularPath.CGPath;

    // Configure the apperence of the circle
    circle.fillColor = [UIColor blackColor].CGColor;
    circle.strokeColor = [UIColor blackColor].CGColor;
    circle.lineWidth = 0;

    imgViewToClipCircular.layer.mask=circle;