码迷,mamicode.com
首页 > 其他好文 > 详细

涂鸦画板

时间:2015-12-08 08:39:55      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

#import "ViewController.h"

#import "DrawView.h"

@interface ViewController ()

@end

@implementation ViewController

-(void)loadView{

    self.view = [[DrawView alloc]init];

    self.view.backgroundColor = [UIColor whiteColor];

}

- (void)viewDidLoad {

    [super viewDidLoad];    

}

@end

////////////////////////////////////////////////////////////

#import "DrawView.h"

@interface DrawView()

@end

@implementation DrawView

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        _lineArray = [NSMutableArray array];

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

        btn.frame = CGRectMake(100, 420, 100, 40);

        btn.backgroundColor=[UIColor yellowColor];

        

        [btn setTitle:@"撤销" forState:UIControlStateNormal];

        [btn addTarget:self action:@selector(undoDraw) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:btn];

    }

    return self;

}

//撤销操作

-(void)undoDraw{

    [_lineArray removeLastObject];//删除最后一条线

    [self setNeedsDisplay];//View重绘,自动重绘

}

//每次手指开始触摸,增加一个新的数组,数组记录划过的点,利用这些点绘画

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

 

    [_lineArray addObject:[NSMutableArray arrayWithCapacity:1]];

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touche = [touches anyObject];

    CGPoint point = [touche locationInView:self];

    //数组里需要id类型

    NSValue *value = [NSValue valueWithCGPoint:point];

    //value装到_lineArray的最后一个元素(数组)里

    [[_lineArray lastObject] addObject:value];

    [self setNeedsDisplay];//重绘界面

}

 

-(void)drawRect:(CGRect)rect{

 

    CGContextRef context = UIGraphicsGetCurrentContext();//获得上下文

    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);//画笔颜色

    for (int i=0; i<[_lineArray count]; i++) {

        NSMutableArray *pointArray = [[NSMutableArray alloc]initWithArray:[_lineArray objectAtIndex:i]];

        for (int j=0; j<[pointArray count]-1; j++) {

            //遍历所有的点

            NSValue *a = [pointArray objectAtIndex:j];

            CGPoint p1 = [a CGPointValue];

            NSValue *b = [pointArray objectAtIndex:j+1];

            CGPoint p2 = [b CGPointValue];

            

            CGContextMoveToPoint(context, p1.x, p1.y);

            CGContextAddLineToPoint(context, p2.x, p2.y);

        }        

    }

    //在当前的图形上下文中,根据画笔的颜色和画笔的路径,进行绘制

    CGContextStrokePath(context);

}

@end

涂鸦画板

标签:

原文地址:http://www.cnblogs.com/liuyingjie/p/5028063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!