本文主要是介绍自制画板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
效果
重点代码
@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;}//每条线开始画都要初始化pathUIBezierPath * 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
{//删除pathUIBezierPath * lastBezierPath = [mBezierPathArray lastObject];[lastBezierPath removeAllPoints];[mBezierPathArray removeLastObject];//删除layerNSArray * lastShapeLayerArray = [mShapeLayerArray lastObject];[mShapeLayerArray removeLastObject];for (CAShapeLayer * layer in lastShapeLayerArray) {[layer removeFromSuperlayer];}}
这篇关于自制画板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!