时间有限我们就不多说,直接上代码,这里实现使用了分类,名称大家可以随意发挥
获取图片上某个点的颜色值(不包含alpha)
XXXXXXXX.h
文件
@interface UIImage (XXXXXXXX)
/// 获取图片上某个点的RGB值(不包含alpha)。
- (nullable NSArray<NSNumber *> *)pixelColorFromPoint:(CGPoint)point;
@end
XXXXXXXX.m
文件
@implementation UIImage (XXXXXXXX)
/// 获取图片上某个点的颜色值(不包含alpha)。
- (nullable NSArray<NSNumber *> *)pixelColorFromPoint:(CGPoint)point {
// 判断点是否超出图像范围
if (!CGRectContainsPoint(CGRectMake(0, 0, self.size.width, self.size.height), point)) return nil;
// 将像素绘制到一个1×1像素字节数组和位图上下文。
NSInteger pointX = trunc(point.x);
NSInteger pointY = trunc(point.y);
CGImageRef cgImage = self.CGImage;
CGFloat width = self.size.width;
CGFloat 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);
// 将指定像素绘制到上下文中
CGContextTranslateCTM(context, -pointX, pointY - height);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), cgImage);
CGContextRelease(context);
CGFloat red = (CGFloat)pixelData[0];
CGFloat green = (CGFloat)pixelData[1];
CGFloat blue = (CGFloat)pixelData[2];
return @[@(red), @(green), @(blue)];
}
@end
收工
网友评论