1. 程式人生 > >object-c畫筆的簡單實現

object-c畫筆的簡單實現

畫筆簡單實現。之前也是對這個一點兒概念也沒得,然後在網上找了一個列子。就明白了。

思路。主要是呼叫兩個方法。就是觸控拖動和觸控拖動結束的方法。

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);
    }
}