Reputation: 181290
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?.
Upvotes: 3
Views: 1200
Reputation: 481
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];
}
Upvotes: 4