画笔简单实现。之前也是对这个一点儿概念也没得,然后在网上找了一个列子。就明白了。
思路。主要是调用两个方法。就是触摸拖动和触摸拖动结束的方法。
1.触摸拖动方法里面:将所有触摸的点获得,放到一个数组里面,然后再绘制每一个点。
2.触摸拖动结束:将所有点数组放到新的一个数组里面。然后将存点的那个数组清空掉。不然你画得所有线条都是相连的。
具体来看看代码:
1.添加两个数组
//每次触摸结束前经过的点用来连成线
@property (nonatomic,strong) NSMutableArray *pointArray;
//保存线条的数组
@property (nonatomic,strong) NSMutableArray *arrayLine;
2.然后再在触摸拖动事件里面把滑动的每一个点保存到点数组,在拖动结束里面保存每条线。然后清空点数组
//画笔触摸的所有点
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
//去除每一个点
CGPoint myBeginPoint = [touch locationInView:self];
NSString *strPoint = NSStringFromCGPoint(myBeginPoint);
[self.pointArray addObject:strPoint];
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if(self.pointArray!=nil)
{
[self.arrayLine addObject:self.pointArray];//将点得数组放入线的数组
}
self.pointArray = [NSMutableArray array];//将点数组清空
}
3.最后重写drawRectr方法,将所有点和线绘制出来。就成了一个画板了
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, self.sliderWidth.value);
CGContextSetLineJoin(context, kCGLineJoinRound);//设置拐角样式
CGContextSetLineCap(context, kCGLineCapRound);//设置线头样式
if(self.arrayLine.count>0)
{
//将里面的线条画出来
for(int i = 0;i<self.arrayLine.count;i++)
{
NSArray *array = [NSArray arrayWithArray:self.arrayLine[i]];
if(array.count>0)
{
CGPoint myStartPoint = CGPointFromString(array[0]);
//将画笔移动到指定的点
CGContextMoveToPoint(context, myStartPoint.x, myStartPoint.y);
for(int j = 1;j<array.count;j++)
{
CGPoint myEndPoint = CGPointFromString(array[j]);
CGContextAddLineToPoint(context, myEndPoint.x, myEndPoint.y);
}
[_blackColor setStroke];//设置画笔颜色
CGContextStrokePath(context);
}
}
}
if(self.pointArray.count>0)
{
//划线
CGPoint startPoint = CGPointFromString(self.pointArray[0]);
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
for(int i = 1;i<self.pointArray.count;i++)
{
CGPoint tempPoint = CGPointFromString(self.pointArray[i]);
CGContextAddLineToPoint(context, tempPoint.x, tempPoint.y);
}
[_blackColor setStroke];//设置画笔颜色
CGContextStrokePath(context);
}
}