我正在尝试编写一个方法,该方法返回 UIView 中某个区域(由 CGRect 表示)内最常见的颜色。
这是我迄今为止开发的代码,但它似乎不起作用。 NSLog 输出列出了每个像素的颜色,即使我添加了一些红色条纹,它也始终显示白色(255,255,255)。
如果有人能告诉我问题出在哪里,我将不胜感激:
- (UIColor *) dominantColorInRect:(CGRect)rect
{
UIColor * dominantColor = nil;
NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * rect.size.width;
NSUInteger bitsPerComponent = 8;
unsigned int bitmapSize = bytesPerRow * rect.size.height;
unsigned char pixelData[bitmapSize];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixelData,
rect.size.width,
rect.size.height,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
[self.layer renderInContext:context];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
if (pixelData) {
unsigned long size = sizeof(pixelData)/sizeof(unsigned char);
for (int i = 0; i < size; i += bytesPerPixel) {
UIColor * color = [UIColor colorWithRed:pixelData[0]/255.0
green:pixelData[1]/255.0
blue:pixelData[2]/255.0
alpha:pixelData[3]/255.0];
if (color) {
const CGFloat * colors = CGColorGetComponents( color.CGColor);
CGFloat red = colors[0]*255;
CGFloat green = colors[1]*255;
CGFloat blue = colors[2]*255;
NSLog(@"This Color: %f,%f,%f",red,green,blue);
NSInteger count = [[dictionary objectForKey:color] integerValue];
count++;
[dictionary setObject:[NSNumber numberWithInt:count] forKey:color];
}
}
}
int highestFrequency = 0;
for (id color in dictionary) {
NSInteger count = [[dictionary objectForKey:color] integerValue];
//NSInteger count = [object[1] integerValue];
if (count > highestFrequency) {
highestFrequency = count;
dominantColor = color;
}
}
return dominantColor;
}
最佳答案
您重复读取第一个像素的值
UIColor * color = [UIColor colorWithRed:pixelData[0]/255.0
green:pixelData[1]/255.0
blue:pixelData[2]/255.0
alpha:pixelData[3]/255.0];
我认为应该是这样的
UIColor * color = [UIColor colorWithRed:pixelData[i]/255.0
green:pixelData[i+1]/255.0
blue:pixelData[i+2]/255.0
alpha:pixelData[i+3]/255.0];
关于ios - 在 CGRect 中查找主色的算法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21339667/