[英]CALayer mask not working correctly
我试图使用它的图层的掩码属性将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
一种可能性是系统实际上并没有使用setFrame:
来设置视图的几何体。 它可以使用setCenter:
和setBounds:
. 另一种可能性是系统根本没有设置视图的几何体,并且在添加遮罩层之前,只在[super initWithFrame:frame]
调用中设置了一次。
无论如何,你应该覆盖layoutSubviews
而不是覆盖setFrame:
:
- (void)layoutSubviews {
[super layoutSubviews];
self.layer.mask.frame = self.bounds;
}
以下按预期工作:
- (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不起作用,但这增加了与可伸缩图像配合良好的好处。
您可以在屏幕上覆盖UIView drawRect()方法的自定义外观。 尝试使用以下方法。
//code for drawRect()
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddRect(context,ImageFrame);
CGContextClip(context);
CGContextClearRect(context,ImageFrame);
[super drawRect:rect];
它会使您的视图在imageFrame区域中透明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.