iOS: Drawing just portions of a UImage

邮差的信 提交于 2019-12-01 06:22:20

问题


I am trying to draw just a custom portion of a UIImage (i.e.: I would like to reveal the portion of the UIImage user touches) and I am having reasonable results by using mask property of the layer.

Something like this on my 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];

Then, on drawRect:

- (void)drawRect:(CGRect)rect
{
    [img drawInRect:rect];
}

It works. I am just seeing the portion of the image defined by maskPath.

However, doesn't look that that's the best way of approaching this issue. So my question is: What would be the best way of drawing just a custom portion (it could be any shape) of an image in iOS SDK?.


回答1:


One thing you could try is simply clipping instead of creating an extra layer. e.g.

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


来源:https://stackoverflow.com/questions/10214897/ios-drawing-just-portions-of-a-uimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!