ios - 从 UIColor 创建 UIImage 以用作 UIButton 的背景图像

我正在创建这样的彩色图像:

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)

https://stackoverflow.com/questions/6496441/

相关文章:

ios - 如何查看 NSString 是否以某个其他字符串开头?

objective-c - NSAttributedString 的 boundingRectWit

objective-c - 为什么要使用 ivar?

objective-c - xcode中Base SDK、iOS部署目标、Target、Projec

iphone - 以编程方式切换到 TabBar 选项卡 View ?

ios - 如何确定 NSDate 是否是今天?

objective-c - 在objective-c中YES/NO,TRUE/FALSE和true/

ios - 两个 NSDate 之间的天数

ios - 如何手动弃用成员

ios - 如何在 iPhone 上创建圆角 UILabel?