3
我想實現一個方法,給定一個UIView內的CGRect,返回該矩形中最常用的顏色。iOS:如何確定UIView中CGRect中頻率最高的顏色?
我已閱讀類似問題的答案,並且已經通過Apple文檔瞭解這些答案中列出的代碼,最終結果是令人頭疼的。
我會很感激,如果有人可以解釋如何做到這一點。
UPDATE
我已經成功通過擴展rojkarc的鏈接展示了colorAtPixel方法來創建工作的功能。我很確定這不是那麼有效。如果有人有改進它的建議,我會很感激。
- (UIColor *) dominantColorInRect:(CGRect)rect
{
UIColor * dominantColor = nil;
NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * 1;
NSUInteger bitsPerComponent = 8;
unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
for (int x = rect.origin.x; x <= rect.size.width; x++) {
for (int y = 0; y <= rect.size.height; y++) {
context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -x, -y);
[self.layer renderInContext:context];
CGContextRelease(context);
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) {
NSInteger count = [[dictionary objectForKey:color] integerValue];
count++;
[dictionary setObject:[NSNumber numberWithInt:count] forKey:color];
}
}
}
CGColorSpaceRelease(colorSpace);
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;
}
[Here](http://stackoverflow.com/a/9554125/653513)也是Ole Begemann的代碼的鏈接,它包含帶有'ColorAtPixel'方法的'UIImage'類別。 –