我正在创建这样的彩色图像:
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,
[[UIColor redColor] CGColor]);
// [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ;
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
然后将其用作按钮的背景图片:
[resultButton setBackgroundImage:img forState:UIControlStateNormal];
使用 redColor 效果很好,但是我想使用 RGB 颜色(如注释行所示)。当我使用 RGB 颜色时,按钮背景没有改变。
我错过了什么?
最佳答案
我围绕 UIButton 创建了一个类别,以便能够设置按钮的背景颜色并设置状态。您可能会发现这很有用。
@implementation UIButton (ButtonMagic)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
[self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}
+ (UIImage *)imageFromColor:(UIColor *)color {
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
这将是我本月开源的一组帮助类别的一部分。
swift 2.2
extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
swift 3.0
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
用作
let img = UIImage.from(color: .black)
关于ios - 从 UIColor 创建 UIImage 以用作 UIButton 的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6496441/