简单画板(用UIBezierPath和CAShapeLayer几行代码)

@interface CustomView ()

@property (nonatomic, strong) CAShapeLayer *shaperLayer;
@property (nonatomic, strong) UIBezierPath *bezierPath;

@end



@implementation CustomView

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

    self.bezierPath = [UIBezierPath bezierPath];
    [self.bezierPath moveToPoint:startPoint]; //起始点
    
    self.shaperLayer = [[CAShapeLayer alloc] init];
    self.shaperLayer.fillColor = [[UIColor clearColor] CGColor];
    self.shaperLayer.strokeColor = [[UIColor greenColor] CGColor];
    self.shaperLayer.lineWidth = 20;
    self.shaperLayer.lineCap = kCALineCapRound; //端点圆角
    self.shaperLayer.lineJoin = kCALineJoinRound; //连接点圆角

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

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = touches.anyObject;
    CGPoint currentPoint = [touch locationInView:self];
    [self.bezierPath addLineToPoint:currentPoint]; //连接点

    self.shaperLayer.path = self.bezierPath.CGPath;
}

@end

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容