這是一個很簡單的塗鴉闆,隻能在這裡畫線條而已~
首先建立一個可變數組:
#import "PaintView.h"
//延展 在延展中聲明的屬性隻能屬于這個類
@interface PaintView ()
//用于儲存所有線段的數組
@property(nonatomic, retain)NSMutableArray *allLines;
@end
對這個數組進行懶加載~
- (NSMutableArray *)allLines
{
if (!_allLines) {
self.allLines = [NSMutableArray array];//右邊是便利構造器的建立,左邊是getter方法
}
return _allLines;
}
開始畫線條:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//擷取觸摸的起始點
UITouch *aTouch = touches.anyObject;
CGPoint startPoint = [aTouch locationInView:self.superview];
//通過貝塞爾曲線對象來記錄目前觸摸移動産生的軌迹點
UIBezierPath *path = [UIBezierPath bezierPath];
//通過貝塞爾曲線對象記錄起始點
[path moveToPoint:startPoint];
//将曲線儲存在數組中
[self.allLines addObject:path];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//擷取目前觸摸産生的目前點
UITouch *atouch = touches.anyObject;
CGPoint currentPoint = [atouch locationInView:self.superview];
//擷取目前建立的貝塞爾曲線
UIBezierPath *path = self.allLines.lastObject;
//添加目前觸摸的軌迹點
[path addLineToPoint:currentPoint]; //r讓目前視圖重繪界面
//一旦調用此方法,視圖對象會自動調用drawRect:方法來繪制自己的界面
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
// Drawing code
//設定畫筆的顔色
[[UIColor redColor]setStroke];
//通過周遊數組來繪制每一條畫闆上的曲線
for (UIBezierPath *path in self.allLines) {
//設定貝塞爾曲線的線寬
path.lineWidth = 5;
//在視圖上重繪貝塞爾曲線
[path stroke];
}
}
這裡設計到了系統的方法:事件觸發; 線條是由一個個點組成的,觸摸開始的時候是一個點,移動的時候也是一個點,這些點連接配接起來就成了一條線~
可以進一步的豐富這個塗鴉闆的功能,比如增加幾個按鈕,可以改變它的線條的寬度,顔色,删除線條,撤銷删除等功能;
請多多指教~~