美文网首页iOS DeveloperiOS开发攻城狮的集散地
iOS:可自由选择各种颜色,宽度,带橡皮擦,可撤回操作的画板涂鸦

iOS:可自由选择各种颜色,宽度,带橡皮擦,可撤回操作的画板涂鸦

作者: Theendisthebegi | 来源:发表于2018-07-03 10:42 被阅读104次

最近由于项目需求需要用到一个画板功能,除了能实现实时涂鸦之外,还要实现动态改变线条颜色,线条宽度,还要实现橡皮擦,撤回上一步操作,清理画板,保存画板到相册等功能...


image

这里是提供几种常用颜色供选择,此外还提供了颜色选择器,可自由选择线条颜色


image
画线部分代码
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);

CGContextRef context = UIGraphicsGetCurrentContext();

[self.image drawAtPoint:CGPointZero];

CGContextSetLineWidth(context, self.lineWidth);

CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);

CGContextSetLineCap(context, kCGLineCapRound);

if(_isEraserBlock()){

    CGContextSetBlendMode(context, kCGBlendModeClear);

}

CGContextMoveToPoint(context, previousPoint.x, previousPoint.y);

CGContextAddQuadCurveToPoint(context, previousPoint.x, previousPoint.y, currentPoint.x, currentPoint.y);

CGContextStrokePath(context);

self.image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

画板是基于UIImageView的,所以保存相册时直接将image保存就行

清理就是将image置为nil,并将保存的point全部移除

self.image = nil;

[self.pointArray removeAllObjects];

撤销则是将上次操作的所有point移除,并重新绘制,此处的showLines就是将所有点重新绘制一遍

if (!self.pointArray.count) return;

[self.pointArray removeObject:self.pointArray.lastObject];

self.image = nil;

[self showLines];

橡皮擦则是设置下当前绘制的BlendMode

   if(model.isEraser){
        
        CGContextSetBlendMode(context, kCGBlendModeClear);
    }

具体操作逻辑细节和UI等是参考微信的图片编辑中的画板

github代码地址

相关文章

网友评论

    本文标题:iOS:可自由选择各种颜色,宽度,带橡皮擦,可撤回操作的画板涂鸦

    本文链接:https://www.haomeiwen.com/subject/yudduftx.html