Hi.. I am developing an application in which i have to pick the color from the image at pixel location .
It is not giving me proper color , it gives me random color. I am displaying that color in image view
Here is the code Snippet.....
-(void)colorDummyView:(UIColor *)clrForDummyView { colorView=[[UIView alloc] initWithFrame:CGRectMake(30.0, 300.0, 30.0, 30.0)]; colorView.backgroundColor=clrForDummyView; [self.view addSubview:colorView]; }
(void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* touch = [touches anyObject]; CGPoint point = [touch locationInView:self.view];
UIColor *clr = [self getPixelColorAtLocation:point]; [self colorDummyView:clr]; }
(UIColor*) getPixelColorAtLocation:(CGPoint)point { UIColor* color = nil; UIImage *img=[UIImage imageNamed:@"color-stack.png"]; CGImageRef inImage = [img CGImage]; CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage]; if (cgctx == NULL) { return nil; }
size_t w = CGImageGetWidth(inImage); size_t h = CGImageGetHeight(inImage); CGRect rect = {{0,0},{w,h}};
CGContextDrawImage(cgctx, rect, inImage);
unsigned char* data = CGBitmapContextGetData (cgctx); if (data != NULL) {
int offset = 4*((w*round(point.y))+round(point.x)); int alpha = data[offset]; int red = data[offset+1]; int green = data[offset+2]; int blue = data[offset+3]; NSLog(@"offset: %i colors: RGB A %i %i %i %i",offset,red,green,blue,alpha); color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
}
CGContextRelease(cgctx); if (data) { free(data); }
return color; }
(CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {
CGContextRef context = NULL; CGColorSpaceRef colorSpace; void * bitmapData; int bitmapByteCount; int bitmapBytesPerRow;
size_t pixelsWide = CGImageGetWidth(inImage); size_t pixelsHigh = CGImageGetHeight(inImage);
bitmapBytesPerRow = (pixelsWide * 4); bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == NULL) { fprintf(stderr, "Error allocating color space\n"); return NULL; }
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; }