IOS(UI)_手势2(简单画板)

简单画板

先创建一个UIView 名字AppView

重写initWithFrame方法:
-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        //UIView的背景颜色
        self.backgroundColor = [UIColor whiteColor];
        //是否可以交互
        self.userInteractionEnabled = YES;
        //是否允许多个手指
        self.multipleTouchEnabled = YES;
        linesArray = [NSMutableArray array];
    }
    return self;
}

然后在本类的drawRect:

    - (void)drawRect:(CGRect)rect {

    //拿到画板
    CGContextRef context = UIGraphicsGetCurrentContext();

    //设置画笔粗细和颜色
    CGContextSetLineWidth(context, 5);
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:34/255.0 green:199/255.0 blue:1.0 alpha:1].CGColor);


    for (int i = 0; i < linesArray.count; i++)
    {
        NSArray *pointsArray = linesArray[i];

        //拿到第一个点
        CGContextMoveToPoint(context, [pointsArray[0] CGPointValue].x, [pointsArray[0] CGPointValue].y);

        for (int j = 1; j< pointsArray.count; j++)
        {
            //对剩下坐标每个坐标进行绘画
            CGContextAddLineToPoint(context, [pointsArray[j] CGPointValue].x, [pointsArray[j] CGPointValue].y);
        }

    }
    //绘画
    CGContextStrokePath(context);
}

添加手势:

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"手指放在上面");
    //的到手指开始坐标
    points = [NSMutableArray array];

    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self];
    [pointArray addObject:[NSValue valueWithCGPoint:point]];

    //把开始坐标放进数组 pointArray为全局变量NSMutableArray
    [linesArray addObject:pointArray];
    NSLog(@"%lu",(unsigned long)linesArray.count);
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"手指移动");
    //的到手指坐标
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self];
    //大数组嵌套小数组的方法
    [pointArray addObject:[NSValue valueWithCGPoint:point]];

    //调用drawRect方法 重新绘画
    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"手指离开屏幕");

}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值