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

标签 ios objective-c uibutton uiimage

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

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/

相关文章:

objective-c - 写入驻留在 Xcode 项目目录中的文件

ios - 编辑 CGPath 的 "vertices"?

ios私钥和证书不配对

ios - 缩放时如何在 UIView 周围保持一致的 2px 边框?

ios - 在具有动态数据的 WidgetKit 中,如何为新的 WidgetKit 指定默认的 IntentConfiguration?

ios - 固定大小的 UIView,在 View 中居中

ios - @property (nonatomic,retain) UISegmentedControl *colorChooser 中的警告;

ios - UIButton上的事件指示器

ios - Swift - UIButton 覆盖 setSelected

swift - UIButton 标题 + 使用 Paintcode 应用程序的图像