子衿沉夜
这是我对UIImage采样颜色的解决方案。此方法将请求的像素渲染为1px大型RGBA缓冲区,并将生成的颜色值作为UIColor对象返回。这比我见过的大多数其他方法快得多,并且只使用很少的内存。对于像颜色选择器这样的东西,它应该可以很好地工作,在任何给定的时间你通常只需要一个特定像素的值。的UIImage + Picker.h#import <UIKit/UIKit.h>@interface UIImage (Picker)- (UIColor *)colorAtPosition:(CGPoint)position;@end的UIImage + Picker.m#import "UIImage+Picker.h"@implementation UIImage (Picker)- (UIColor *)colorAtPosition:(CGPoint)position {
CGRect sourceRect = CGRectMake(position.x, position.y, 1.f, 1.f);
CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, sourceRect);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *buffer = malloc(4);
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
CGContextRef context = CGBitmapContextCreate(buffer, 1, 1, 8, 4, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0.f, 0.f, 1.f, 1.f), imageRef);
CGImageRelease(imageRef);
CGContextRelease(context);
CGFloat r = buffer[0] / 255.f;
CGFloat g = buffer[1] / 255.f;
CGFloat b = buffer[2] / 255.f;
CGFloat a = buffer[3] / 255.f;
free(buffer);
return [UIColor colorWithRed:r green:g blue:b alpha:a];}@end