使用CALayers使遮盖区域周围的区域透明?

时间:2013-04-27 05:23:39

标签: objective-c transparency calayer mask

我正在尝试将图像裁剪为不规则形状,但我需要将被删除的区域设为透明。

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];

这将适当地裁剪图像,但视图的背景颜色为白色,因此仍然可见。我试过让其他图层透明,但它没有用。

(自我和子视图都引用相同的视图)

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

是否有可能创造出我想要达到的效果?

1 个答案:

答案 0 :(得分:0)

我尝试了同样的事情,这里是确切的代码:

// 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;
}

按预期它对我有用。背景是透明的。然后我尝试添加

self.backgroundColor = [UIColor clearColor];

到代码的开头并没有任何改变,图像显示在剪切到路径的透明背景上。

我认为问题可能出在其他地方。

iPhone