how to draw CALayer with line path like simulate eraser effect?

感情迁移 提交于 2019-11-30 10:51:30

Your code is close, but what you need is a custom layer class that has a gray background, and draws the path as transparent. You can do that with code like this

RevealLayer.h

@interface RevealLayer : CALayer
@property (strong, nonatomic) UIBezierPath *drawingPath;
@end

RevealLayer.m

@implementation RevealLayer
- (UIBezierPath *)drawingPath
{
    if ( !_drawingPath )
    {
        _drawingPath = [UIBezierPath new];
        [_drawingPath moveToPoint:CGPointZero];
        [_drawingPath setLineWidth:20.0];
        [_drawingPath setLineCapStyle:kCGLineCapRound];
    }
    return( _drawingPath );
}

- (void)drawInContext:(CGContextRef)context
{
    UIGraphicsPushContext( context );

    [[UIColor darkGrayColor] set];
    CGContextFillRect( context, self.bounds );

    CGContextSetBlendMode( context, kCGBlendModeClear );
    [self.drawingPath stroke];

    UIGraphicsPopContext();
}
@end

Then the code for the custom view class is similar to what you already have. However, the setup is a little different and you don't need to implement the drawRect: method.

CustomView.m

@interface CustomView()
@property (strong, nonatomic) RevealLayer *revealLayer;
@end

@implementation CustomView
- (void)setup
{
    self.userInteractionEnabled = YES;
    [self setMultipleTouchEnabled:NO];

    self.image = [UIImage imageNamed:@"transformers.jpg"];

    self.revealLayer = [RevealLayer new];
    self.revealLayer.frame = self.bounds;
    self.revealLayer.backgroundColor = [[UIColor clearColor] CGColor];
    [self.revealLayer setNeedsDisplay];

    [self.layer addSublayer:self.revealLayer];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];

    [self.revealLayer.drawingPath moveToPoint:location];
    [self.revealLayer setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];

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