這是一個很簡單的塗鴉板,只能在這裏畫線條而已~
首先創建一個可變數組:
#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];
}
}
這裏設計到了系統的方法:事件觸發; 線條是由一個個點組成的,觸摸開始的時候是一個點,移動的時候也是一個點,這些點連接起來就成了一條線~
可以進一步的豐富這個塗鴉板的功能,比如增加幾個按鈕,可以改變它的線條的寬度,顏色,刪除線條,撤銷刪除等功能;
請多多指教~~