這取決於該問題的答案的改善和@Anomie
的實現
首先,把這個在您的UIButton
類,或者您的視圖控制器的開始。它將從UIColor
轉換爲RGBA
值,您稍後需要該值。
typedef enum { R, G, B, A } UIColorComponentIndices;
@implementation UIColor (EPPZKit)
- (CGFloat)redRGBAValue {
return CGColorGetComponents(self.CGColor)[R];
}
- (CGFloat)greenRGBAValue {
return CGColorGetComponents(self.CGColor)[G];
}
- (CGFloat)blueRGBAValue {
return CGColorGetComponents(self.CGColor)[B];
}
- (CGFloat)alphaRGBAValue {
return CGColorGetComponents(self.CGColor)[A];
}
@end
現在,請確保您在IB中具有自定義圖像按鈕,帶有灰度圖像和正確的框架。這是再編程方式創建自定義圖像按鈕相當好,更容易,因爲:
- 可以讓IB加載圖像,而不必手動加載它
- 可以調節按鈕,看看它在視覺上IB
- 您的IB看起來更像你的應用程序在運行時
- 您不必手動設置幀
假設你有按鈕在IB(接近底部將支持對於有它編程方式創建),此方法添加到您的視圖控制器或按鈕崽類:
- (UIImage*)customImageColoringFromButton:(UIButton*)customImageButton fromColor:(UIColor*)color {
UIImage *customImage = [customImageButton.imageView.image copy];
UIGraphicsBeginImageContext(customImageButton.imageView.frame.size); {
CGContextRef X = UIGraphicsGetCurrentContext();
[customImage drawInRect: customImageButton.imageView.frame];
// Overlay a colored rectangle
CGContextSetBlendMode(X, kCGBlendModeColor) ;
CGContextSetRGBFillColor (X, color.redRGBAValue, color.greenRGBAValue, color.blueRGBAValue, color.alphaRGBAValue);
CGContextFillRect (X, customImageButton.imageView.frame);
// Redraw
[customImage drawInRect:customImageButton.imageView.frame blendMode: kCGBlendModeDestinationIn alpha: 1.0];
customImage = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
return customImage;
}
然後,您將需要調用它的設置方法,在您的視圖控制器或按鈕的子類,並設置的ImageView的該按鈕將其:
[myButton.imageView setImage:[self customImageColoringFromButton:myButton fromColor:desiredColor]];
如果您是使用IB創建按鈕不,使用此方法:
- (UIImage*)customImageColoringFromImage:(UIImage*)image fromColor:(UIColor*)color fromFrame:(CGRect)frame {
UIImage *customImage = [image copy];
UIGraphicsBeginImageContext(frame.size); {
CGContextRef X = UIGraphicsGetCurrentContext();
[customImage drawInRect: frame];
// Overlay a colored rectangle
CGContextSetBlendMode(X, kCGBlendModeColor) ;
CGContextSetRGBFillColor (X, color.redRGBAValue, color.greenRGBAValue, color.blueRGBAValue, color.alphaRGBAValue);
CGContextFillRect (X, frame);
// Redraw
[customImage drawInRect:frame blendMode: kCGBlendModeDestinationIn alpha: 1.0];
customImage = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
return customImage;
}
而且與調用它:
[self.disclosureButton.imageView setImage:[self customImageColoringFromImage:[UIImage imageNamed:@"GemTop_Dull.png"] fromColor:desiredColor fromFrame:desiredFrame]];
我對看似多餘{}您的代碼示例非常好奇 - 什麼做這些做 – Rhubarb
他們使代碼更清晰/封裝變量 –
如果你想支持視網膜圖像,請確保您使用'UIGraphicsBeginImageContextWithOptions(targetSize,NO,0.0);'而不是'UIGraphicsBeginImageContext(targetSize);'。參數「NO」和「0.0」分別表示使用不透明上下文(YES或NO值)和縮放因子(0.0表示設備縮放因子,任何其他值用於顯式縮放因子)。 –