gpt4 book ai didi

ios - 在 CGRect 中查找主色的算法不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:28:53 25 4
gpt4 key购买 nike

我正在尝试编写一种方法,该方法返回 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com