Demo:http://download.csdn.net/detail/u012881779/9408857
功能:使用用户在UIImageView上的触摸点从UIImage获取该点的UIColor(RGB)
先使用Category方式拓展UIImage
#import "UIImage+ColorSelect.h"
@implementation UIImage (ColorSelect)
- (UIColor *)colorAtPixel:(CGPoint)point {
// Cancel if point is outside image coordinates
if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) {
return nil;
}
NSInteger pointX = trunc(point.x);
NSInteger pointY = trunc(point.y);
CGImageRef cgImage = self.CGImage;
NSUInteger width = self.size.width;
NSUInteger height = self.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * 1;
NSUInteger bitsPerComponent = 8;
unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGContextRef context = CGBitmapContextCreate(pixelData,
1,
1,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Draw the pixel we are interested in onto the bitmap context
CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
CGContextRelease(context);
// Convert color values [0..255] to floats [0.0..1.0]
CGFloat red = (CGFloat)pixelData[0] / 255.0f;
CGFloat green = (CGFloat)pixelData[1] / 255.0f;
CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end
再创建控制器从UIImagView获取CGPoint
#import "SelectColorViewController.h"
#import "UIImage+ColorSelect.h"
@interface SelectColorViewController ()
//素材图片不要拉伸去适配分辨率,那样获取的颜色会不准确
@property (weak, nonatomic) IBOutlet UIImageView *sourceImgView;
@property (weak, nonatomic) IBOutlet UIImageView *resultImagView;
@end
@implementation SelectColorViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//完成选择
-(void)finishedAction:(CGPoint)point{
UIColor *tempColor = [_sourceImgView.image colorAtPixel:point];
[_resultImagView setBackgroundColor:tempColor];
NSLog(@"\n_x=%f,y=%f",point.x,point.y);
}
//Touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint tempPoint = [touch locationInView:_sourceImgView];
[self finishedAction:tempPoint];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
}
@end
示意图: