Search code examples
objective-ctransparencycalayermask

Make area around masked region transparent with CALayers?


I'm trying to crop an image to an irregular shape, but I need to make the area that was removed transparent.

Inside subclass of UIView

   CALayer *myLayer = [CALayer layer];
   CAShapeLayer *mask = [CAShapeLayer layer];    
    myLayer.frame = self.bounds;
    myLayer.contents =  (id)[self.picture CGImage];
    mask.path = path;
    myLayer.mask = mask;
    [self.layer addSublayer:myLayer];

This will crop the image appropriately, but the background color of the view is white and therefore still visible. I've tried making the other layers transparent, but it has not worked.

(self and subview both refer to same view)

[self layer].backgroundColor = [UIColor clearColor].CGColor //no change
[self layer].opacity = 0; //makes entire view transparent
subView.backgroundColor = [UIColor clearColor]; // entire view becomes transparent

Is it possible to create the effect I'm trying to achieve?


Solution

  • I tried the same thing, here is the exact code:

    // In KMViewController.m
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor lightGrayColor];
        CGRect frame = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
        KMView *view = [[KMView alloc] initWithFrame:frame];
        view.center = self.view.center;
        [self.view addSubview:view];
    }
    
    // In KMView.m
    - (id)initWithFrame:(CGRect)frame
     {
        self = [super initWithFrame:frame];
        if (self) {
            // self.backgroundColor = [UIColor clearColor];
            CALayer *layer = [CALayer layer];
            CAShapeLayer *mask = [CAShapeLayer layer];
            layer.frame = self.bounds;
            UIImage *image = [UIImage imageNamed:@"orange"];
            layer.contents = (id)image.CGImage;
            CGPathRef path = CGPathCreateWithEllipseInRect(frame, NULL);
            mask.path = path;
            CGPathRelease(path);
            layer.mask = mask;
            [self.layer addSublayer:layer];
        }
        return self;
    }
    

    It worked for me as expected. The background was transparent. Then I tried adding

    self.backgroundColor = [UIColor clearColor];
    

    to the beginning of the code and nothing changed, the image was showing on a transparent background clipped to the path.

    I think the problem might be somewhere else.

    iPhone