Skip to content

Instantly share code, notes, and snippets.

@mindbrix
Created March 30, 2011 15:57
Show Gist options
  • Save mindbrix/894665 to your computer and use it in GitHub Desktop.
Save mindbrix/894665 to your computer and use it in GitHub Desktop.
A UIImage category to read a single pixel as a UIColor
//
// UIView+getUIColor.h
// PRL_iPad_Catalogue
//
// Created by Nigel Barber on 30/03/2011.
// Copyright 2011 Mindbrix. All rights reserved.
//
@interface UIImage (getUIColor)
- (UIColor *)getUIColor :(int)xx :(int)yy;
@end
//
// UIView+getUIColor.m
// PRL_iPad_Catalogue
//
// Created by Nigel Barber on 30/03/2011.
// Copyright 2011 Mindbrix. All rights reserved.
//
#import "UIView+getUIColor.h"
@implementation UIImage (getUIColor)
- (UIColor *)getUIColor :(int)xx :(int)yy
{
// First get the image into your data buffer
CGImageRef imageRef = [self CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGImageGetColorSpace( imageRef );
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
CGFloat red = (rawData[byteIndex] * 1.0) / 255.0;
CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
free(rawData);
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment