- (CGContextRef)createARGBBitmapContextWithImage:(UIImage*)image {
// Get image width, height
size_t pixelsWide = CGImageGetWidth(image.CGImage);
size_t pixelsHigh = CGImageGetHeight(image.CGImage);
// Declare the number of bytes per row
NSIntegerbitmapBytesPerRow = (pixelsWide *4);
NSIntegerbitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
// Use the generic RGB color space.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if(colorSpace ==NULL) {
return NULL;
}
// Allocate memory for image data
void*bitmapData =malloc( bitmapByteCount );
if(bitmapData ==NULL) {
CGColorSpaceRelease( colorSpace );
return NULL;
}
// Create the bitmap context
CGContextRef context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedFirst);
if(context ==NULL) {
free(bitmapData);
}
// release colorspace before returning
CGColorSpaceRelease( colorSpace );
returncontext;
}
- (UIColor*)getPixelColorAtPoint:(CGPoint)point Image:(UIImage*)image
{
UIColor* color =nil;
CGImageRefinImage = image.CGImage;
// Create bitmap context to draw the image into
CGContextRef cgctx = [self createARGBBitmapContextWithImage:image];
if(cgctx ==NULL) {
returnnil;/* error */
}
size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRectrect = {{0,0},{w,h}};
// Draw the image to the bitmap context
CGContextDrawImage(cgctx, rect, inImage);
// get image data
unsignedchar* data =CGBitmapContextGetData(cgctx);
if(data !=NULL) {
//offset locates the pixel in the data from x,y.
//4 for 4 bytes of data per pixel, w is width of one row of data.
intoffset =4*((w*round(point.y))+round(point.x));
intalpha = data[offset];
intred = data[offset+1];
intgreen = data[offset+2];
intblue = data[offset+3];
//NSLog(@"offset: %i colors: RGB A %i %i %i %i",offset,red,green,blue,alpha);
color = [UIColorcolorWithRed:(red/255.0f)green:(green/255.0f)blue:(blue/255.0f)alpha:(alpha/255.0f)];
}
//release the context
CGContextRelease(cgctx);
// Free image data
if(data) {
free(data);
}
returncolor;
}