標籤:
建立一個以OC為開發語言的IOS工程,建立一個類繼承與UIView
重寫一下方法並實現
//在.h檔案裡面聲明兩個執行個體變數{ CGPoint _startpoint;//記錄點擊滑動時的位置 NSMutableArray* _marray;//記錄滑動時的位置 }//在.m檔案裡面//重寫初始化方法-(id)initWithFrame:(CGRect)frame{ if(self==[super initWithFrame:frame]){ self.backgroundColor=[UIColor lightGrayColor];//設定背景初始化為灰色 _marray=[NSMutableArray new]; } return self;}//觸碰開始方法-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{ UITouch* touch = [touches anyObject];//擷取到點擊時任意的一個值 _startpoint = [touch locationInView:self];//擷取點擊時的位置 NSMutableArray *pointArray = [NSMutableArray new];// //轉換為對象 NSValue *value = [NSValue valueWithCGPoint:_startpoint]; //將存有點擊位置的value存到建立的數組中 [pointArray addObject:value]; [_marray addObject:pointArray];}//滑鼠滑動時的方法-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent* )event{ //跟開始方法差不多,只是會擷取_marray數組最後一個,往裡面添加擷取到得位置 NSMutableArray *pointArray = [_marray lastObject]; UITouch* touch=[touches anyObject]; CGPoint currentPoint = [touch locationInView:self]; NSValue* value=[NSValue valueWithCGPoint:currentPoint]; [pointArray addObject:value]; //這個方法是和繪畫方法呼應 [self setNeedsDisplay];//表示邊繪邊畫}//滑鼠結束時的方法-(void)touchesEnded:(NSSet*) touches withEvent:(UIEvent*)event{}//繪畫方法-(void)drawRect:(CGRect)rect{ CGContextRef cgrf = UIGraphicsGetCurrentContext();//設定筆畫 //筆畫的粗細 CGContextSetLineWidth(cgrf,2.0f); //筆畫的顏色 CGContextSetStrokeColorWithColor(cgrf,[UIColor yellowColor].CGColor); for (NSMutableArray* pointArr in _marray) { for (int i=0; i<pointArr.count-1; i++) { NSValue* value=pointArr[i]; CGPoint apoint=[value CGPointValue]; //將畫筆移動到指定的點 CGContextMoveToPoint(cgrf, apoint.x, apoint.y); NSValue* nextvalue=pointArr[i+1]; CGPoint nextapoint=[nextvalue CGPointValue]; // 將畫筆從現在的點與給定的點(針對函數的參數而言)之間連線 CGContextAddLineToPoint(cgrf, nextapoint.x, nextapoint.y); } } CGContextStrokePath(cgrf); }
注意在ViewController.m裡面實現它
匯入#import"Draw.h"
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view=[[Draw alloc]initWithFrame:[UIScreen mainScreen].bounds];}
本人建立的是Draw,只需要換自訂的檔案名稱就可以
就這樣一個簡單的畫板就完成了
跟複雜的可以在畫板上添加控制項,換畫筆顏色
IOS 學習筆記---一個最基本的畫板(純程式碼實現)