好久没有自己写点东西了,昨天看到前公司的一个小功能,挺感兴趣的,就自己做了个类似于手绘板的功能。废话不多说,上图上代码。
@property (nonatomic, strong) NSMutableArray *LayerArray;
@property (nonatomic, strong) HBShapLayer *drawLayer;
@property (nonatomic, strong) UIBezierPath *beganPath;
//线宽
@property (nonatomic, assign) CGFloat lineWidth;
//线的颜色
@property (nonatomic, strong) UIColor *lineColor;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint beganPoint = [touch locationInView:self];
[self drawBeganPoint:beganPoint];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
//上一个点的坐标
CGPoint previousPoint = [touch previousLocationInView:self];
CGPoint middlePoint = midPoint(previousPoint,currentPoint);
[self drawControlPoint:middlePoint EndPoint:currentPoint];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
CGPoint previousPoint = [touch previousLocationInView:self];
CGPoint middlePoint = midPoint(previousPoint,currentPoint);
[self drawControlPoint:middlePoint EndPoint:currentPoint];
}
线条起点位置:
- (void)drawBeganPoint:(CGPoint)point
{
HBShapLayer *drawLayer = [HBShapLayer layer];
drawLayer.lineWidth = self.lineWidth;
drawLayer.fillColor = [UIColor clearColor].CGColor;
drawLayer.strokeColor = self.lineColor.CGColor;
_drawLayer = drawLayer;
_drawLayer.isPen = YES;
[self.layer addSublayer:_drawLayer];
[_LayerArray addObject:drawLayer];
UIBezierPath *beganPath = [UIBezierPath bezierPath];
[beganPath moveToPoint:point];
_beganPath = beganPath;
}
更新线条的位置:
- (void)drawControlPoint:(CGPoint)controlPoint EndPoint:(CGPoint)point
{
[_beganPath addQuadCurveToPoint:point controlPoint:controlPoint];
_drawLayer.path = _beganPath.CGPath;
}
// 计算中间点
CGPoint midPoint(CGPoint p1, CGPoint p2)
{
return CGPointMake((p1.x + p2.x) * 0.5, (p1.y + p2.y) * 0.5);
}
这个方法是将UIView转为UIImage:
注意UIGraphicsBeginImageContextWithOptions
这个方法的第二个和第三个参数,如果将第二个参数设置为yes的话,保存的图片会出现模糊的情况.
//将UIView转成UIImage
-(UIImage *)getImageFromView:(UIView *)theView
{
// 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
UIGraphicsBeginImageContextWithOptions(theView.bounds.size, NO, [UIScreen mainScreen].scale);
[theView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
有什么错误和疏漏,欢迎指正,附上demo地址。