標籤:
定義一個繼承於NSObject的model對象,用於儲存
線的顏色,路徑及線寬
#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>//一定匯入UIKit架構@interface PathModel : NSObject@property(nonatomic,assign)CGMutablePathRef path;//路徑(需要調用set方法retain)@property(nonatomic,strong)UIColor *color;//顏色@property(nonatomic,assign)CGFloat lineWidth;//線寬@end//記得要將路徑計數值加一,複寫set方法#import "PathModel.h"@implementation PathModel-(void)dealloc{ CGPathRelease(_path);}- (void)setPath:(CGMutablePathRef)path{ //使路徑的計數值加一,這樣在DrawView中釋放路徑後,model中仍然存在,不會出現野指標 CGPathRetain(path); _path = path;}@end
DrawView中的實現代碼
#import "DrawView.h"#import "PathModel.h"@implementation DrawView-(instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { //設定預設值 _lineWidth = 1; _color = [UIColor blackColor]; } return self;}- (void)drawRect:(CGRect)rect { //如果可變數組不是空的,則需要重新繪製之前的路徑 if (_pathArray.count>0) { for (int i = 0; i<_pathArray.count; i++) { //遍曆數組中的所有元素 取出model中的屬性並繪製之前的線條 PathModel *model = _pathArray[i]; CGContextRef context = UIGraphicsGetCurrentContext(); CGMutablePathRef path = model.path; UIColor *color = model.color; CGFloat width = model.lineWidth; //繪製 CGContextAddPath(context, path); //設定填充顏色 [color set]; //設定線寬 CGContextSetLineWidth(context, width); //設定頭尾及連接點的類型為圓的, CGContextSetLineJoin(context, kCGLineJoinRound); CGContextSetLineCap(context, kCGLineCapRound); CGContextDrawPath(context, kCGPathStroke); } } //當_LinePath不為空白的時候,說明開始繪製新的線條,顏色和線寬就是在視圖控制器中通過block塊傳遞過來的參數 if (_LinePath != nil) { CGContextRef context = UIGraphicsGetCurrentContext(); [_color set]; CGContextSetLineWidth(context, _lineWidth); CGContextAddPath(context, _LinePath); CGContextDrawPath(context, kCGPathStroke); } }-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ //取得手指開始觸摸的點的座標 CGPoint p = [[touches anyObject] locationInView:self]; //建立路徑 _LinePath = CGPathCreateMutable(); //獲得路徑開始的點的座標 CGPathMoveToPoint(_LinePath, NULL, p.x, p.y);}-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ //獲得手指一動過程中經過的點的座標 CGPoint p = [[touches anyObject]locationInView:self]; //將這些點添加到路徑中 CGPathAddLineToPoint(_LinePath, NULL, p.x,p.y); //重新繪製 [self setNeedsDisplay];}-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ //建立一個可變數組,存放model對象,(model中有顏色,線寬,路徑三個屬性) if (_pathArray==nil) { _pathArray = [[NSMutableArray alloc]init]; } //建立model對象,並且給model中的屬性賦值 PathModel *model = [[PathModel alloc]init]; model.path = _LinePath; model.lineWidth = _lineWidth; model.color = _color; //將model存放到可變數組中 [_pathArray addObject:model]; //手指結束觸摸時將路徑釋放掉 CGPathRelease(_LinePath); _LinePath = nil; }- (void)undo{ if (_pathArray.count>0) { [_pathArray removeLastObject]; [self setNeedsDisplay]; }}- (void)clear{ if (_pathArray.count>0) { [_pathArray removeAllObjects]; [self setNeedsDisplay]; }}@end
iOS --製作畫板 --2