#import "ColorPickerViewController.h"
#import <CoreGraphics/CoreGraphics.h>
@implementation ColorPickerViewController
@synthesize outputLabel, pictureView;
#pragma mark -
#pragma mark Launch Methods
- (void)viewWillAppear:(BOOL)animated
{
UIImage *colorWheelImage = [UIImage imageNamed:@"colorWheel1.png"];
self.pictureView.image = colorWheelImage;
[self createCGContextWithImage:colorWheelImage];
[super viewWillAppear:animated];
}
- (void)dealloc
{
[outputLabel release];
[pictureView release];
free(pixelData);
[super dealloc];
}
#pragma mark -
#pragma mark Touch Methods
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.view.backgroundColor = [self pixelColorAtLocation:[[touches anyObject] locationInView:self.pictureView]];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
self.view.backgroundColor = [self pixelColorAtLocation:[[touches anyObject] locationInView:self.pictureView]];
}
#pragma mark -
#pragma mark Pixel Data Methods
- (void)createCGContextWithImage:(UIImage*)image
{
NSLog(@"CGContext Created Image");
CGImageRef imageRef = [image CGImage];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger imageRefHeight = CGImageGetHeight(imageRef);
imageRefWidth = CGImageGetWidth(imageRef);
pixelData = malloc(imageRefWidth * imageRefHeight * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = (bytesPerPixel * imageRefWidth);
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(pixelData, imageRefWidth, imageRefHeight, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextDrawImage(context, CGRectMake(0, 0, imageRefWidth, imageRefHeight), imageRef);
CGContextRelease(context);
}
- (UIColor*)pixelColorAtLocation:(CGPoint)point
{
int offset = 4 * ((imageRefWidth * round(point.y)) + round(point.x));
int red = pixelData[offset];
int green = pixelData[offset+1];
int blue = pixelData[offset+2];
int alpha = pixelData[offset+3];
self.outputLabel.text = [NSString stringWithFormat:@"Red:%i\nGreen:%i\nBlue:%i\nAlpha:%i", red, green, blue, alpha];
return [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
}
@end