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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值