我正在尝试获取 UIImage 中心 16 像素的平均 UIColor,但是生成的颜色永远不会接近正确。我在这里做错了什么?点参数是正确的,我已经验证过了。我还有另一种方法,它使用同样的点返回中心像素的 UIColor,效果很好。
+ (UIColor*)getAverageColorForImage:(UIImage *)image atLocation:(CGPoint)point
{
int radialSize = 2;
int xStartPoint = point.x - radialSize;
int yStartPoint = point.y - radialSize;
int xEndPoint = point.x + radialSize;
int yEndPoint = point.y + radialSize;
CGImageRef rawImageRef = [image CGImage];
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef));
const UInt8 *rawPixelData = CFDataGetBytePtr(data);
NSUInteger bytesPerRow = CGImageGetBytesPerRow(rawImageRef);
NSUInteger stride = CGImageGetBitsPerPixel(rawImageRef) / 8;
unsigned int red = 0;
unsigned int green = 0;
unsigned int blue = 0;
for(int row = yStartPoint; row < yEndPoint; row++)
{
const UInt8 *rowPtr = rawPixelData + bytesPerRow * row;
for(int column = xStartPoint; column < xEndPoint; column++)
{
red += rowPtr[0];
green += rowPtr[1];
blue += rowPtr[2];
rowPtr += stride;
}
}
CFRelease(data);
CGFloat f = 1.0f / (255.0f * (yEndPoint - yStartPoint) * (xEndPoint - xStartPoint));
return [UIColor colorWithRed:f * red green:f * green blue:f * blue alpha:1.0f];
}