今天用OC語言來做實現(xiàn)一個簡單的畫板功能. 做起來很簡單就不啰嗦了...代碼呈上:
首先,我們創(chuàng)建一個繼承自UIView的類 在這里RootView:
聲明一個數組,用來保存所有的連線 每一個劃過的每一條線都是數組里面的一個元素
@property(nonatomic,retain)NSMutableArray *lineArray;
初始化一個撤銷按鈕 點擊按鈕撤銷最后一次劃線
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.lineArray = [NSMutableArray arrayWithCapacity:1];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(20, 600, 100, 40);
[button setTitle:@"返回" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
return self;
}
-(void)buttonDidClicked:(UIButton *)sender{
[_lineArray removeLastObject];
[self setNeedsDisplay];
}
其實我們可以這樣理解,我們在落筆的那一刻,是提條線的開始 而在移動的過程當中進行連線:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSMutableArray *pointArray = [NSMutableArray arrayWithCapacity:1];
//吧存放點的數組放進一個大的數組中 相當于用一個大的數組來存放所有用點來組成的線
[_lineArray addObject:pointArray];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
NSLog(@"point = %@",NSStringFromCGPoint(point));
NSMutableArray *pointArray = [_lineArray lastObject];
NSValue *pointValue = [NSValue valueWithCGPoint:point];
[pointArray addObject:pointValue];
//重繪界面
[self setNeedsDisplay];
}
涂鴉的方法
//涂鴉的方法
-(void)drawRect:(CGRect)rect{
//得到上下文 1 在drawrect拿到上下文 2 通過一個Image圖片拿到上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//設置畫筆的顏色
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
//設置畫筆的粗細
CGContextSetLineWidth(context, 2.0);
for (int i = 0; i < [_lineArray count]; i++) {
NSMutableArray *pointArray = [_lineArray objectAtIndex:i];
for (int j = 0; j <(int)pointArray.count - 1; j++) {
//拿出小數組之中的兩個點
NSValue *firstPointValue = [pointArray objectAtIndex:j];
NSValue *secondPointValue = [pointArray objectAtIndex:j+1];
CGPoint firstPoint = [firstPointValue CGPointValue];
CGPoint seconePoint = [secondPointValue CGPointValue];
//把筆觸移動一個點
CGContextMoveToPoint(context, firstPoint.x, firstPoint.y);
//筆觸和另一個點形成一個路徑
CGContextAddLineToPoint(context, seconePoint.x, seconePoint.y);
}
}
//真正繪制
CGContextStrokePath(context);
}
運行一個程序 我們可以看到如下結果 ,此時一個簡單的畫板功能就實現(xiàn)了,我們還可以添加其他一些信息,比如 將信息保存到相冊 在這里不再提及,大家自己摸索