標籤:style blog http color io os ar 使用 for
之前提過繪製映像首先需要取得圖形內容物件(CGContextRef),系統中維護一個CGContextRef的棧,在UI控制項的drawRect方法調用前,系統會為當前繪圖環境建立一個圖形內容物件並且置於CGContextRef棧頂,通過UIGraphicsGetCurrentContext()可以取得這個映像內容物件。我們也可以建立自己的映像內容物件,quartz 2d提供了相應的api給開發人員建立各種內容物件,當我們使用UIKit在IOS記憶體中繪圖時,建立內容相關的工作更加簡單,只需要調用UIGraphicsBeginImageContextWithOptions即可建立一個基於記憶體繪圖的上下文
- (void)drawRect:(CGRect)rect{ //建立一個基於位元影像的上下文(context),並將其設定為當前上下文(context) //繪圖區域大小 | 是否透明 | 縮放因子 //UIGraphicsBeginImageContextWithOptions(rect.size, YES, 1); //透明度預設YES 縮放因子1.0 UIGraphicsBeginImageContext(rect.size); //擷取映像內容物件 CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor magentaColor].CGColor); CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); //繪製橢圓 CGContextStrokeRect(context, CGRectMake(20, 20, 100, 100)); //繪製矩形 CGContextFillEllipseInRect(context, CGRectMake(150, 20, 100, 100)); //繪製文字 [@"this is a jok" drawAtPoint:CGPointMake(20, 150) withAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:30],NSForegroundColorAttributeName:[UIColor redColor]}]; //擷取繪圖上下文中的圖片 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); //結束繪圖 UIGraphicsEndImageContext(); //將圖片顯示到介面上 [image drawInRect:rect]; //圖片儲存到沙箱中 NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"pic.png"]; NSLog(@"%@",path); [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];}
從上例中我們可以看到,在記憶體中繪圖的步驟和在view上繪圖的步驟完全一樣,記憶體中繪製完圖片後也可以顯示到視圖上,或者儲存到應用沙箱中,使用記憶體繪圖的上下文,我們可以很方便的實現繪圖板的功能
@implementation ZLTView { CGPoint _firstPoint; CGPoint _lastPoint; CGContextRef _imageContext; UIImage *_image;}- (id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { UIGraphicsBeginImageContext(self.frame.size); _imageContext = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(_imageContext, [UIColor purpleColor].CGColor); CGContextSetLineWidth(_imageContext, 5); } return self;}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint touchPoint = [touch locationInView:self]; _firstPoint = touchPoint;}- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint touchPoint = [touch locationInView:self]; _lastPoint = touchPoint; CGContextMoveToPoint(_imageContext, _firstPoint.x, _firstPoint.y); CGContextAddLineToPoint(_imageContext, _lastPoint.x, _lastPoint.y); CGContextDrawPath(_imageContext, kCGPathStroke); _image = UIGraphicsGetImageFromCurrentImageContext(); [self setNeedsDisplay]; _firstPoint = _lastPoint;}- (void)drawRect:(CGRect)rect{ [_image drawInRect:rect];}
IOS影像處理(6)在記憶體上下文中繪圖