废话不多说,直接上代码。
创建一个UIImage的Category
#import <UIKit/UIKit.h>
@interface UIImage (ColorWithPicture)
- (UIColor*)colorWithPicture:(CGPoint)point;
@end
#import "UIImage+ColorWithPicture.h"
@implementation UIImage (ColorWithPicture)
- (UIColor *)colorWithPicture:(CGPoint)point {
CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage));
const UInt8 *data = CFDataGetBytePtr(pixelData);
NSUInteger width = self.size.width;
int pixelInfo = ((width * point.y) + point.x) * 4;
CGFloat red = (CGFloat)data[pixelInfo] / 255.0f;
CGFloat green = (CGFloat)data[pixelInfo + 1] / 255.0f;
CGFloat blue = (CGFloat)data[pixelInfo + 2] / 255.0f;
CGFloat alpha = (CGFloat)data[pixelInfo + 3] / 255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end
使用方法
UIImage *image = [UIImage imageNamed:@"image.png"];
self.view.backgroundColor = [image colorWithPicture:CGPointMake(1.0f, 1.0f)];