Quartz 2D是一個二維圖形繪製引擎,支持iOS環境和Mac OS X環境,官方文檔:Quartz 2D Programming Guide。html
1、座標體系ios
這樣的座標體系就致使咱們使用Quartz 2D畫的圖是倒轉的,咱們要作如下處理才能獲得咱們想要的圖片效果:app
1.畫布延Y軸下移heightide
2.對Y軸作垂直翻轉測試
這2個步驟的代碼爲:ui
1 CGContextTranslateCTM(context, 0, height); 2 CGContextScaleCTM(context, 1.0, -1.0);
測試代碼爲:spa
//代碼1 - (void)drawRect:(CGRect)rect { CGContextRef context=UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(context, 1, 0, 0, 1); CGContextFillRect(context, CGRectMake(0, 100, 100, 100)); NSString *text=@"文字"; UIFont *font=[UIFont systemFontOfSize:14]; [text drawAtPoint:CGPointMake(0, 200) withAttributes:font.fontDescriptor.fontAttributes]; UIImage *img=[UIImage imageNamed:@"gg.jpg"]; [img drawInRect:CGRectMake(0, 300, 100, 100)]; }
//代碼2 -(id)initWithFrame:(CGRect)frame { if (self=[super initWithFrame:frame]) { [self setBackgroundColor:[UIColor redColor]]; UIImageView *imgview=[[UIImageView alloc] initWithFrame:self.bounds]; CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB(); float width=self.bounds.size.width; float height=self.bounds.size.height; //256=10000000 int bitsPerComponent=8; //RGBA*8*width int bytesPerRow=4*8*width; CGContextRef context=CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault); //翻轉畫布 CGContextTranslateCTM(context, 0, height); CGContextScaleCTM(context, 1.0, -1.0); UIGraphicsPushContext(context); //畫布透明 //CGContextFillRect(context, self.bounds); CGContextSetRGBFillColor(context, 1, 0, 0, 1); CGContextSetRGBStrokeColor(context, 0, 1, 0, 1); CGContextFillRect(context, CGRectMake(0, 100, 100, 100)); NSString *text=@"文字"; UIFont *font=[UIFont systemFontOfSize:14]; [text drawAtPoint:CGPointMake(0, 200) withAttributes:font.fontDescriptor.fontAttributes]; UIImage *img=[UIImage imageNamed:@"gg.jpg"]; [img drawInRect:CGRectMake(0, 300, 100, 100)]; CGImageRef cgimg = CGBitmapContextCreateImage(context); UIImage *resultImg = [UIImage imageWithCGImage:cgimg]; CGContextRelease(context); CGColorSpaceRelease(colorSpace); CGImageRelease(cgimg); imgview.image=resultImg; [self addSubview:imgview]; } return self; }
2段代碼實現的效果同樣,代碼1並無作翻轉操做,那是由於UIKit在UIGraphicsGetCurrentContext()獲得的畫布已經幫咱們適應好了UIKit的座標體系。3d
轉載請註明出處:http://www.cnblogs.com/bandy/p/4341538.htmlcode