iPhone 构造位图的函数

 

Java代码 
  1. // Courtesy of Apple, Create Bitmap with Alpha/RGB values  
  2. CGContextRef CreateARGBBitmapContext (CGImageRef inImage, CGSize size)  
  3. {  
  4.     CGContextRef    context = NULL;  
  5.     CGColorSpaceRef colorSpace;  
  6.     void *          bitmapData;  
  7.     int             bitmapByteCount;  
  8.     int             bitmapBytesPerRow;  
  9.       
  10.     size_t pixelsWide = size.width;  
  11.     size_t pixelsHigh = size.height;  
  12.     bitmapBytesPerRow   = (pixelsWide * 4); //ARGB  
  13.     bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);  
  14.     colorSpace = CGColorSpaceCreateDeviceRGB();  
  15.       
  16.     if (colorSpace == NULL)  
  17.     {  
  18.         fprintf(stderr, "Error allocating color space\n");  
  19.         return NULL;  
  20.     }  
  21.       
  22.     // allocate the bitmap & create context  
  23.     bitmapData = malloc( bitmapByteCount );  
  24.     if (bitmapData == NULL)  
  25.     {  
  26.         fprintf (stderr, "Memory not allocated!");  
  27.         CGColorSpaceRelease( colorSpace );  
  28.         return NULL;  
  29.     }  
  30.       
  31.     context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8,  
  32.                                      bitmapBytesPerRow, colorSpace,  
  33.                                      kCGImageAlphaPremultipliedFirst);  
  34.     if (context == NULL)  
  35.     {  
  36.         free (bitmapData);  
  37.         fprintf (stderr, "Context not created!");  
  38.     }  
  39.       
  40.     CGColorSpaceRelease( colorSpace );  
  41.     return context;  
  42. }  
  43.   
  44. // Return a C-based bitmap of the image data inside an image  
  45. unsigned char *RequestImagePixelData(UIImage *inImage)  
  46. {  
  47.     CGImageRef img = [inImage CGImage];  
  48.     CGSize size = [inImage size];  
  49.       
  50.     CGContextRef cgctx = CreateARGBBitmapContext(img, size);  
  51.     if (cgctx == NULL) return NULL;  
  52.       
  53.     CGRect rect = {{0,0},{size.width, size.height}};  
  54.     CGContextDrawImage(cgctx, rect, img);  
  55.     unsigned char *data = CGBitmapContextGetData (cgctx);  
  56.     CGContextRelease(cgctx);  
  57.       
  58.     return data;  
  59. }  

 

 

使用位图某像素:

[UIColor 

colorWithRed: (float) (bitmap[startByte+1]/255.0f)

green: (float) (bitmap[startByte+2]/255.0f)

blue:  (float) (bitmap[startByte+3]/255.0f)

alpha(float)(bitmap[startByte]]

原文地址:https://www.cnblogs.com/KiloNet/p/1807343.html