2014-01-24 64 views
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; 
} 

回答

2

以下算法:

  1. 創建從UIView的PNG圖像的矩形內側(代碼見下文)
  2. 你必須通過圖像進行迭代(垂直和horisontal)
  3. 您必須創建顏色直方圖:

要創建顏色直方圖,必須獲取像素的顏色在一個給定的位置(像這裏:http://www.markj.net/iphone-uiimage-pixel-color/) 而且你必須計算(並收集)給定顏色的頻率。

創建圖像:

if(UIGraphicsBeginImageContextWithOptions != NULL){ 
       UIGraphicsBeginImageContextWithOptions(self.view.layer.frame.size, NO, 0.0); 
      }else { 
       UIGraphicsBeginImageContext(self.view.layer.frame.size); 
      } 
      [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
      img = UIGraphicsGetImageFromCurrentImageContext(); 
      size_t imageSize = CGImageGetBytesPerRow(img.CGImage) * CGImageGetHeight(img.CGImage); 
      NSLog(@"imageSize: %zu",(imageSize/(1024*1024))); 
      UIGraphicsEndImageContext(); 

創建直方圖:谷歌吧,很多的僞/ Objective-C代碼可用。

+1

[Here](http://stackoverflow.com/a/9554125/653513)也是Ole Begemann的代碼的鏈接,它包含帶有'ColorAtPixel'方法的'UIImage'類別。 –