自制画板

xiaoxiao2021-02-28  84

效果

重点代码

@implementation GSDrawFunView { NSMutableArray * mShapeLayerArray; // 总layer数组,里面有好多线,每条线由下面数组组成 NSMutableArray * mCurrentShapeLayerArray; // 当前画的线的layer数组 NSMutableArray * mBezierPathArray; // 所有path数组 UIColor * mCurrentColor; UIView * mDrawBoardView; } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { UITouch * touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; //控制画板位置,防止线画出画板 if (point.x < mDrawBoardView.x || point.y < mDrawBoardView.y || point.x > CGRectGetMaxX(mDrawBoardView.frame) || point.y > CGRectGetMaxY(mDrawBoardView.frame)) { return; } //每条线开始画都要初始化path UIBezierPath * currentBezierPath = [[UIBezierPath alloc]init]; [currentBezierPath moveToPoint:point]; [mBezierPathArray addObject:currentBezierPath]; //每条线开始画都要初始化layer数组 mCurrentShapeLayerArray = [[NSMutableArray alloc]init]; } -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { UITouch * touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; if (point.x < mDrawBoardView.x || point.y < mDrawBoardView.y || point.x > CGRectGetMaxX(mDrawBoardView.frame) || point.y > CGRectGetMaxY(mDrawBoardView.frame)) { return; } UIBezierPath * currentBezierPath = [mBezierPathArray lastObject]; [currentBezierPath addLineToPoint:point]; CAShapeLayer * currentLayer = [[CAShapeLayer alloc]init]; currentLayer.path = currentBezierPath.CGPath; currentLayer.fillColor = nil; currentLayer.strokeColor = mCurrentColor.CGColor; currentLayer.lineJoin = kCALineJoinRound; //终点 currentLayer.lineCap = kCALineCapRound; //拐角 currentLayer.lineWidth = 2; [self.layer addSublayer:currentLayer]; [mCurrentShapeLayerArray addObject:currentLayer]; } -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //每条线画完,都要添加到layer数组里 [mShapeLayerArray addObject:mCurrentShapeLayerArray]; } //改变画笔颜色 -(void)changeColorForPaintBrushWithColor:(UIColor *)color { mCurrentColor = color; } //撤销 -(void)remokeLineAction { //删除path UIBezierPath * lastBezierPath = [mBezierPathArray lastObject]; [lastBezierPath removeAllPoints]; [mBezierPathArray removeLastObject]; //删除layer NSArray * lastShapeLayerArray = [mShapeLayerArray lastObject]; [mShapeLayerArray removeLastObject]; for (CAShapeLayer * layer in lastShapeLayerArray) { [layer removeFromSuperlayer]; } }

转载请注明原文地址: https://www.6miu.com/read-54625.html

最新回复(0)