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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6496441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:32:26  来源:igfitidea点击:

Creating a UIImage from a UIColor to use as a background image for UIButton

iosobjective-cuibuttonuiimage

提问by Thorsten

I'm creating a colored image like this:

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

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();

and then use it as the background image of a button:

然后将其用作按钮的背景图像:

[resultButton setBackgroundImage:img forState:UIControlStateNormal];

This works great using the redColor, however I want to use an RGB color (as shown in the commented line). When I use the RGB color, the buttons background isn't changed.

使用 redColor 效果很好,但是我想使用 RGB 颜色(如注释行所示)。当我使用 RGB 颜色时,按钮背景不会改变。

What am I missing?

我错过了什么?

回答by ScottWasserman

I created a category around UIButton to be able to set the background color of the button and set the state. You might find this useful.

我在 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;
}

This will be part of a set of helper categories I'm open sourcing this month.

这将是我本月开源的一组帮助程序类别的一部分。

Swift 2.2

斯威夫特 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

斯威夫特 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!
    }
}

Use as

用于

let img = UIImage.from(color: .black)

回答by ben

Xamarin.iOS solution

Xamarin.iOS 解决方案

 public UIImage CreateImageFromColor()
 {
     var imageSize = new CGSize(30, 30);
     var imageSizeRectF = new CGRect(0, 0, 30, 30);
     UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
     var context = UIGraphics.GetCurrentContext();
     var red = new CGColor(255, 0, 0);
     context.SetFillColor(red);
     context.FillRect(imageSizeRectF);
     var image = UIGraphics.GetImageFromCurrentImageContext();
     UIGraphics.EndImageContext();
     return image;
 }

回答by Jesse Rusak

Are you using ARC? The problem here is that you don't have a reference to the UIColorobject that you're trying to apply; the CGColoris backed by that UIColor, but ARC will deallocate the UIColorbefore you have a chance to use the CGColor.

你在使用ARC吗?这里的问题是您没有对要应用的UIColor对象的引用;在CGColor由支持UIColor,但ARC会回收UIColor你有机会使用之前CGColor

The clearest solution is to have a local variable pointing to your UIColorwith the objc_precise_lifetimeattribute.

最明确的解决方案是让一个局部变量指向你UIColorobjc_precise_lifetime属性。

You can read more about this exact case on this article about UIColor and short ARC lifetimesor get more details about the objc_precise_lifetimeattribute.

您可以在这篇有关 UIColor 和短 ARC 生命周期的文章中阅读有关此确切案例的更多信息,或获取有关objc_precise_lifetime属性的更多详细信息。

回答by iGerm

Add the dots to all values:

将点添加到所有值:

[[UIColor colorWithRed:222./255. green:227./255. blue: 229./255. alpha:1] CGColor]) ;

Otherwise, you are dividing float by int.

否则,您将 float 除以 int。

回答by aknew

I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0

我想 227./255 中的 255 被认为是一个整数,除法总是返回 0

回答by bdunagan

Your code works fine. You can verify the RGB colors with Iconfactory's xScope. Just compare it to [UIColor whiteColor].

你的代码工作正常。您可以使用Iconfactory 的 xScope验证 RGB 颜色。只需将其与[UIColor whiteColor].

回答by Muzamil Hassan

CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);