iOS:仅绘制UImage的一部分

我想绘制一个UIImage的自定义部分(即:我想揭示UIImage用户触摸的部分),我有合理的结果,通过使用该layer mask属性。

在我的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中的图像的自定义部分(可以是任何形状)的最佳方式什么?

你可以尝试的一件事就是剪裁,而不是创build一个额外的图层。 例如

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