iPhone 构造位图的函数

 

// Courtesy of Apple, Create Bitmap with Alpha/RGB values
CGContextRef CreateARGBBitmapContext (CGImageRef inImage, CGSize size)
{
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    void *          bitmapData;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;
	
    size_t pixelsWide = size.width;
    size_t pixelsHigh = size.height;
    bitmapBytesPerRow   = (pixelsWide * 4); //ARGB
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);
    colorSpace = CGColorSpaceCreateDeviceRGB();
	
	if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }
	
    // allocate the bitmap & create context
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL)
    {
        fprintf (stderr, "Memory not allocated!");
        CGColorSpaceRelease( colorSpace );
        return NULL;
    }
	
    context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8,
									 bitmapBytesPerRow, colorSpace,
									 kCGImageAlphaPremultipliedFirst);
    if (context == NULL)
    {
        free (bitmapData);
        fprintf (stderr, "Context not created!");
    }
	
    CGColorSpaceRelease( colorSpace );
    return context;
}

// Return a C-based bitmap of the image data inside an image
unsigned char *RequestImagePixelData(UIImage *inImage)
{
	CGImageRef img = [inImage CGImage];
	CGSize size = [inImage size];
    
	CGContextRef cgctx = CreateARGBBitmapContext(img, size);
    if (cgctx == NULL) return NULL;
	
    CGRect rect = {{0,0},{size.width, size.height}};
    CGContextDrawImage(cgctx, rect, img);
	unsigned char *data = CGBitmapContextGetData (cgctx);
	CGContextRelease(cgctx);
	
	return data;
}

 

 

使用位图某像素:

[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]]

你可能感兴趣的:(apple,C++,c,C#)