为CAShapeLayer *maskLayer设置透明背景(iphone)

3

我在UIView上放置了一个UIImageView。 通过使用UIBezierPath绘制了一个形状,现在我想要将其他部分设置为透明。 我的代码如下:

- (void)drawRect:(CGRect)rect
{
    self.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.0];
    imgV.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.0];
    aPath = [UIBezierPath bezierPath];
    CGContextRef aRef ;
    aRef = UIGraphicsGetCurrentContext();
    [[UIColor clearColor] setStroke];
    [[UIColor clearColor] setFill];
    aPath.lineWidth = 2;
    aPath = [UIBezierPath new];
                //path is calculated here using addLineToPoint addArcWithCentre methods
    [aPath fill];
    [aPath stroke];
    [self setClippingPath:aPath :imgV];
    [[[UIColor clearColor] colorWithAlphaComponent:0.0] setFill];
    CGContextFillRect(aRef, rect);
    CGContextFillPath(aRef);
    self.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.0];
    imgV.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.0];
}
- (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView;
{   
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = imgView.frame;
    maskLayer.path = [clippingPath CGPath];
    maskLayer.backgroundColor = [[[UIColor clearColor] colorWithAlphaComponent:0.0] CGColor];
    maskLayer.fillColor = [[UIColor whiteColor] CGColor];

    [imgView removeFromSuperview];
    imgView.layer.mask = maskLayer;

    [self addSubview:imgView];

}   

以下图片显示了输出结果。图像周围的黑色部分应该是透明的。enter image description here请帮助我。

1个回答

0

我认为你可能错过了最后一个调用,可能就在addSubview:之前。

imgView.clipsToBounds = YES;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接