iOS:如何仅绘制UIImage的一部分

3
我正在尝试绘制UIImage的自定义部分(即:我想要展示用户触摸的部分 UIImage),并且通过使用layermask属性,我已经取得了合理的结果。
在我的UIView上实现如下:
UIBezierPath *maskPath = [UIBezierPath bezierPath];
[maskPath setLineWidth:10.0];
[maskPath moveToPoint:CGPointMake(10.0, 10.0)];
[maskPath addLineToPoint:CGPointMake(100.0, 100.0)];
CAShapeLayer *shapeMaskLayer = [CAShapeLayer layer];
shapeMaskLayer.path = maskPath.CGPath;
[self.layer setMask:shapeMaskLayer];

然后,在drawRect中:
- (void)drawRect:(CGRect)rect
{
    [img drawInRect:rect];
}

它起作用了。我只看到由maskPath定义的图像部分。

然而,看起来这不是最好的解决方法。所以我的问题是:在iOS SDK中,绘制图像的任意形状的自定义部分的最佳方法是什么?

1个回答

4
你可以尝试的一件事情是仅仅进行剪裁而不是创建额外的图层。例如:
- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    UIBezierPath *maskPath = [UIBezierPath bezierPath];
    [maskPath setLineWidth:10.0];
    [maskPath moveToPoint:CGPointMake(10.0, 10.0)];
    [maskPath addLineToPoint:CGPointMake(100.0, 100.0)];

    CGContextAddPath(ctx, maskPath.CGPath);
    CGContextClip(ctx)
    [img drawInRect:rect];
}

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