2012-09-11 50 views
1

我有一個黑色輪廓的圓和一個白色填充,我需要以編程方式將白色轉換爲另一種顏色(通過UIColor)。我已經嘗試了一些其他的stackoverflow解決方案,但是它們都沒有正常工作,要麼只是填寫外部或輪廓。將UIImage着色爲不同的顏色,或者,從矢量生成UIImage

我有兩種方法我能做到這一點,但我不確定我將如何得到正確的結果:

色調只是白色對什麼的UIColor應該是,

,或者

從兩個圓圈中製作一個UIImage,其中一個被填充,另一個與黑色重疊。

+0

你的意思,你在畫中的drawRect圓或使用某種類型的形象? –

+0

我需要一個UIImage是24×24,具有UIColor'd圈和黑色的邊框,無論是動態地CoreGraphics中或着色白上黑色版本 –

回答

0

對於這樣簡單的形狀,只需使用CoreGraphics繪製一個正方形和一個圓形 - 添加在您的實現中設置填充顏色的能力。

如果它只是黑色和白色 - 那麼當您知道顏色表示時,將白色更改爲另一種顏色並不困難。不幸的是,編寫和執行這個過程會更復雜......我的建議是直接到CoreGraphics來完成簡單的任務(糟糕的雙關語,抱歉)。

這裏有一個快速演示:

static void InsetRect(CGRect* const pRect, const CGFloat pAmount) { 
    const CGFloat halfAmount = pAmount * 0.5f; 
    *pRect = CGRectMake(pRect->origin.x + halfAmount, pRect->origin.y + halfAmount, pRect->size.width - pAmount, pRect->size.height - pAmount); 
} 

static void DrawBorderedCircleWithWidthInContext(const CGRect pRect, const CGFloat pWidth, CGContextRef pContext) { 
    CGContextSetLineWidth(pContext, pWidth); 
    CGContextSetShouldAntialias(pContext, true); 
    CGRect r = pRect; 
    /* draw circle's border */ 
    CGContextSetRGBStrokeColor(pContext, 0.8f, 0.7f, 0, 1); 
    InsetRect(&r, pWidth); 
    CGContextStrokeEllipseInRect(pContext, r); 
    /* draw circle's fill */ 
    CGContextSetRGBFillColor(pContext, 0, 0, 0.3f, 1); 
    InsetRect(&r, pWidth); 
    CGContextFillEllipseInRect(pContext, r); 
} 
0

擴展一個UIView,只是實現drawRect方法。例如,這將繪製一個帶有黑色輪廓的綠色圓圈。

 - (void)drawRect:(CGRect)rect { 

      [super drawRect:rect]; 

      CGContextRef gc = UIGraphicsGetCurrentContext(); 

      [[UIColor greenColor] setFill]; 
      CGContextFillEllipseInRect(gc, CGRectMake(0,0,24,24)); 

      [[UIColor blackColor] set]; 
      CGContextStrokeEllipseInRect(gc, CGRectMake(0,0,24,24)); 
    } 
5

如果你決定使用兩個圓圈,一白一個黑,那麼你會發現這是很有幫助的。這種方法會給你一個色彩,但它解決了僅對不透明部分着色的問題,這意味着如果你在圓圈周圍提供了一個png透明度的話,它只會着色圓形。因此,不是填充圖像的整個24x24幀,而只填充不透明的部分。這不完全是您的問題,但如果您使用列出的第二個選項,則可能會遇到此問題。

-(UIImage*)colorAnImage:(UIColor*)color :(UIImage*)image{ 

CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height); 
UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale); 
CGContextRef c = UIGraphicsGetCurrentContext(); 
[image drawInRect:rect]; 
CGContextSetFillColorWithColor(c, [color CGColor]); 
CGContextSetBlendMode(c, kCGBlendModeSourceAtop); 
CGContextFillRect(c, rect); 
UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
return result; 

}

+1

謝謝!我一直在尋找這樣的解決方案永遠哈哈。 – user2734823