2013-12-18 35 views
0

我試過使用本文中描述的類別解決方案(How to get the RGB values for a pixel on an image on the iphone)。它似乎不適用於我的情況。在這種情況下無法獲取像素的顏色

我的方案,我畫圈圈響應敲擊手勢:

//mainImageView is an IBOutlet of class UIImageView. So here we simply get a pointer to its image. 
UIImage *mainImage = self.mainImageView.image; 
//Start an image context. 
UIGraphicsBeginImageContextWithOptions(self.mainImageView.bounds.size, NO, 0.0); 
//Save the context in a handy variable for use later. 
CGContextRef context = UIGraphicsGetCurrentContext(); 

for (Ant *ant in self.ants) { //Ant is a subclass of NSObject. 
    //First draw the existing image into the context. 
    [mainImage drawInRect:CGRectMake(0, 0, self.mainImageView.bounds.size.width, self.mainImageView.bounds.size.height)]; 

    // Now draw a circle with position and size specified by the Ant object properties. 
    // Set the width of the line 
    CGFloat lineWidth = ant.size.width/20; 
    CGContextSetLineWidth(context, lineWidth); 
    CGContextSetFillColorWithColor(context, ant.color.CGColor); 
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextBeginPath(context); 
    CGContextAddArc(context, 
        ant.location.x,       //center x coordinate 
        ant.location.y,       //center y coordinate 
        ant.size.width/2 - lineWidth/2,   //radius of circle 
        0.0, 2*M_PI, YES); 
    CGContextDrawPath(context, kCGPathFillStroke); 
} 
self.mainImageView.image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

到目前爲止好。這會按照預期的顏色將圓圈繪製到self.mainImageView.image,並且在重複調用時,會在新位置繪製更多副本。響應某些事件(可能是一個計時器 - 可能是點擊),螞蟻對象的位置會更新,想法是在新位置查看屏幕上的內容,並根據該位置的顏色執行一些操作。另一種方法,moveAnt,包括以下代碼:

CGPoint newLocation = /*calculation of the location is not relevant to this discussion*/ 
UIColor *colorAtNewLocation = [self.mainImageView.image colorAtPosition:newLocation]; 

的值用於紅色,綠色和藍色總是零,和α的值是明顯隨機每個會話,但在會話期間保持不變。

那麼這裏發生了什麼?似乎該類別中的colorAtPosition方法必須期望CGImageRef的格式與上面實際創建的格式不同。是對的嗎?這讓我感到驚訝,因爲它看起來像是爲了擁有一個已知的格式而專門編寫的,所以我決定嘗試一下。

+0

我刪除了這個問題,因爲我認爲問題出現在位置上,但我很確定我已經排序了。現在它似乎在某些時候有效,但大部分時間沒有。當我引用'self.mainImageView.image'時,是否會出現某種緩存?它正在查看一個陳舊的'CGImageRef'? –

回答

0

問題是CGImageRef不知道圖像的比例。通過更改類別中的方法以包含比例參數來解決問題。位置尺寸然後乘以比例以獲得正確的圖像來查詢顏色。