CALayer面具无法正常工作

时间:2012-10-23 03:22:33

标签: ios cocoa-touch core-animation calayer

我试图使用它的图层的mask属性将UIView屏蔽到图像。我看到无数的例子说,“它就是那么容易”。然而,经过相当多的调整后,我似乎无法重现所描述的结果。仅设置图层蒙版会使视图消失。这是我正在使用的代码:

- (void)setMaskImage:(UIImage *)maskImage
{
    _maskImage = maskImage;

    self.layer.mask.contents = (__bridge id)(_maskImage.CGImage);
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self != nil) {
        self.layer.mask = [CALayer layer];
    }

    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    self.layer.mask.frame = self.layer.bounds;
}

这是我试图用来掩盖视图的图像:http://cl.ly/0a300G2r133V

3 个答案:

答案 0 :(得分:6)

一种可能性是系统实际上没有使用setFrame:来设置视图的几何体。它可以使用setCenter:setBounds:。另一种可能性是系统根本没有设置视图的几何体,并且在添加遮罩层之前,只在[super initWithFrame:frame]调用中设置了一次。

无论如何,您应该覆盖setFrame:,而不是覆盖layoutSubviews

- (void)layoutSubviews {
    [super layoutSubviews];
    self.layer.mask.frame = self.bounds;
}

答案 1 :(得分:1)

以下按预期方式工作:

- (void)setMaskImage:(UIImage *)maskImage
{
    if (_maskView == nil) {
        _maskView = [[UIImageView alloc] initWithImage:maskImage];
        _maskView.frame = self.bounds;
        self.layer.mask = _maskView.layer;
    } else {
        _maskView.image = maskImage;
    }
}

- (UIImage *)maskImage
{
    return _maskView.image;
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];

    _maskView.frame = self.bounds;
}

我不确定为什么只使用普通的CALayer不起作用,但这增加了与可伸缩图像配合良好的好处。

答案 2 :(得分:0)

您可以在屏幕上覆盖UIView drawRect()方法的自定义外观。 尝试使用以下方法。

//code for drawRect()

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddRect(context,ImageFrame);
CGContextClip(context);
CGContextClearRect(context,ImageFrame);
[super drawRect:rect];

它会使您的视图在imageFrame区域中透明。

相关问题