注:在iOS中,最好用UIGraphicsBeginImageContextWithOptions来代替底层的CGContext。因为如果你用CGContext的方式创建一个画布(原文:offscreen bitmap,这里理解为一个画布)的话,创建出来的画布的坐标系为bitmap graphics context的方式的,而如果你用UIGraphicsBeginImageContextWithOptions创建画布的话,创建出来的画布坐标系是UIView方式的,这两个坐标系Y轴的坐标是刚好相反的。虽然你可以在最后要显示出来的时候手动转换坐标系为UIView的方式,但是明显这样的性能就不是最佳的了。
1、通过CGContext的方法创建
1 /** 2 * 通过图片获得和图片大小一样的画布 3 * 4 * @param inImage 5 * 6 * @return 返回画布对象 7 */ 8 - (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)inImage { 9 CGContextRef context = NULL; 10 CGColorSpaceRef colorSpace; 11 void * bitmapData; 12 size_t bitmapByteCount; 13 size_t bitmapBytesPerRow; 14 15 // Get image width, height. We'll use the entire image. 16 size_t pixelsWide = CGImageGetWidth(inImage); 17 size_t pixelsHigh = CGImageGetHeight(inImage); 18 19 // Declare the number of bytes per row. Each pixel in the bitmap in this 20 // example is represented by 4 bytes; 8 bits each of red, green, blue, and 21 // alpha. 22 bitmapBytesPerRow = (pixelsWide * 4); 23 bitmapByteCount = (bitmapBytesPerRow * pixelsHigh); 24 25 // Use the generic RGB color space. 26 colorSpace = CGColorSpaceCreateDeviceRGB(); 27 28 if (colorSpace == NULL) 29 { 30 fprintf(stderr, "Error allocating color space\n"); 31 return NULL; 32 } 33 34 // Allocate memory for image data. This is the destination in memory 35 // where any drawing to the bitmap context will be rendered. 36 bitmapData = malloc( bitmapByteCount ); 37 if (bitmapData == NULL) 38 { 39 fprintf (stderr, "Memory not allocated!"); 40 CGColorSpaceRelease( colorSpace ); 41 return NULL; 42 } 43 44 // Create the bitmap context. We want pre-multiplied ARGB, 8-bits 45 // per component. Regardless of what the source image format is 46 // (CMYK, Grayscale, and so on) it will be converted over to the format 47 // specified here by CGBitmapContextCreate. 48 context = CGBitmapContextCreate (bitmapData, 49 pixelsWide, 50 pixelsHigh, 51 8, // bits per component 52 bitmapBytesPerRow, 53 colorSpace, 54 kCGImageAlphaPremultipliedFirst); 55 if (context == NULL) { 56 free (bitmapData); 57 fprintf (stderr, "Context not created!"); 58 } 59 // Make sure and release colorspace before returning 60 CGColorSpaceRelease( colorSpace ); 61 return context; 62 }
2、通过UIGraphicsBeginImageContextWithOptions的方法创建
1 /** 2 * 主要用来创建一个基于位图的图形上下文(这里称之为画布) 3 * 4 * @param size 在调用UIGraphicsGetImageFromCurrentImageContext 时返回的画布的尺寸,这个尺寸是以像素点的方式返回,所以实际宽高的输出是size的值乘上后面提供的scale参数 5 * @param opaque 布尔值,表示图像是否不透明 6 * @param scale 生成bitmap的比例因子,如果设置的值为0的话表示和屏幕的scale一样 7 */ 8 UIGraphicsBeginImageContextWithOptions(size, 0, 0); 9 //获得当前画布 10 CGContextRef context = UIGraphicsGetCurrentContext(); 11 //结束当前的画布操作 12 UIGraphicsEndImageContext();