ios 着色 UIButton 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19829356/
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-31 02:48:22  来源:igfitidea点击:

Color Tint UIButton Image

iosiphoneuibuttonios7uisegmentedcontrol

提问by Logan Shire

I noticed that when I place a white or black UIImageinto a UISegmentedControlit automatically color masks it to match the tint of the segmented control. I thought this was really cool, and was wondering if I could do this elsewhere as well. For example, I have a bunch of buttons that have a uniform shape but varied colors. Instead of making a PNG for each button, could I somehow use this color masking to use the same image for all of them but then set a tint color or something to change their actual color?

我注意到当我将白色或黑色UIImage放入其中时,UISegmentedControl它会自动对其进行颜色遮罩以匹配分段控件的色调。我觉得这真的很酷,想知道我是否也可以在其他地方做这件事。例如,我有一堆形状统一但颜色不同的按钮。不是为每个按钮制作一个 PNG,我可以以某种方式使用这种颜色遮罩为所有按钮使用相同的图像,然后设置色调颜色或其他东西来改变它们的实际颜色吗?

回答by Ric Santos

As of iOS 7, there is a new method on UIImageto specify the rendering mode. Using the rendering mode UIImageRenderingModeAlwaysTemplatewill allow the image color to be controlled by the button's tint color.

从 iOS 7 开始,有一个新的方法UIImage来指定渲染模式。使用渲染模式UIImageRenderingModeAlwaysTemplate将允许图像颜色由按钮的色调颜色控制。

Objective-C

目标-C

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[button setImage:image forState:UIControlStateNormal]; 
button.tintColor = [UIColor redColor];

Swift

迅速

let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red

回答by hashier

As Ric already mentioned in his postyou can set the render mode in code, you can also do this directly in the image catalog, see attached image below. Just set the Render Asto Template Image

正如 Ric 在他的帖子中已经提到的,您可以在代码中设置渲染模式,您也可以直接在图像目录中执行此操作,请参见下面的附图。只需设置Render AsTemplate Image

enter image description here

在此处输入图片说明

CaveatI have had problems with iOS 7 and this approach. So if you use iOS 7 as well you might want to do it in code as well to be sure, as described here.

警告我在使用 iOS 7 和这种方法时遇到了问题。所以,如果你使用的iOS 7,以及你可能想要做的代码,以及可以肯定,作为描述在这里

回答by auco

Custom Buttonsappear in their respective image colors. Setting the button type to "System" in the storyboard (or to UIButtonTypeSystemin code), will render the button's image with the default tint color.

自定义按钮以其各自的图像颜色显示。在情节提要中(或UIButtonTypeSystem在代码中)将按钮类型设置为“系统” ,将使用默认色调呈现按钮的图像。

Button Type System Renders Icons tinted

按钮类型系统呈现有色图标

(tested on iOS9, Xcode 7.3)

(在 iOS9、Xcode 7.3 上测试)

回答by Nick Wargnier

You must set the image rendering mode to UIImageRenderingModeAlwaysTemplatein order to have the tintColoraffect the UIImage. Here is the solution in Swift:

您必须将图像渲染模式设置UIImageRenderingModeAlwaysTemplate为 才能tintColor影响 UIImage。这是 Swift 中的解决方案:

let image = UIImage(named: "image-name")
let button = UIButton()
button.setImage(image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal)
button.tintColor = UIColor.whiteColor()

SWIFT 4x

快速 4 倍

button.setImage(image.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
button.tintColor = UIColor.blue

回答by Ilker Baltaci

If you have a custom button with a background image.You can set the tint color of your button and override the image with following .

如果您有一个带有背景图像的自定义按钮。您可以设置按钮的色调颜色并使用以下内容覆盖图像。

In assets select the button background you want to set tint color.

在资产中选择要设置色调颜色的按钮背景。

In the attribute inspector of the image set the value render as to "Template Image"

在图像的属性检查器中将值渲染设置为“模板图像”

enter image description here

在此处输入图片说明

Now whenever you setbutton.tintColor = UIColor.redyou button will be shown in red.

现在,无论何时设置,button.tintColor = UIColor.red您的按钮都会显示为红色。

回答by henrik-dmg

In Swift you can do that like so:

在 Swift 中,你可以这样做:

var exampleImage = UIImage(named: "ExampleImage.png")?.imageWithRenderingMode(.AlwaysTemplate)

Then in your viewDidLoad

然后在你的 viewDidLoad

exampleButtonOutlet.setImage(exampleImage, forState: UIControlState.Normal)

And to modify the color

并修改颜色

exampleButtonOutlet.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) //your color

EDIT Xcode 8Now you can also just the rendering mode of the image in your .xcassets to Template Image and then you don't need to specifically declare it in the var exampleImageanymore

编辑Xcode中8现在你也可以只是在你的.xcassets到模板图像的图像的渲染模式,然后你就不需要在明确声明它var exampleImage

回答by Kirby Todd

Not sure exactly what you want but this category method will mask a UIImage with a specified color so you can have a single image and change its color to whatever you want.

不确定您想要什么,但此类别方法将使用指定颜色屏蔽 UIImage,因此您可以拥有单个图像并将其颜色更改为您想要的任何颜色。

ImageUtils.h

图像实用程序

- (UIImage *) maskWithColor:(UIColor *)color;

ImageUtils.m

ImageUtils.m

-(UIImage *) maskWithColor:(UIColor *)color 
{
    CGImageRef maskImage = self.CGImage;
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    CGRect bounds = CGRectMake(0,0,width,height);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClipToMask(bitmapContext, bounds, maskImage);
    CGContextSetFillColorWithColor(bitmapContext, color.CGColor);    
    CGContextFillRect(bitmapContext, bounds);

    CGImageRef cImage = CGBitmapContextCreateImage(bitmapContext);
    UIImage *coloredImage = [UIImage imageWithCGImage:cImage];

    CGContextRelease(bitmapContext);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(cImage);

    return coloredImage;    
}

Import the ImageUtils category and do something like this...

导入 ImageUtils 类别并执行以下操作...

#import "ImageUtils.h"

...

UIImage *icon = [UIImage imageNamed:ICON_IMAGE];

UIImage *redIcon = [icon maskWithColor:UIColor.redColor];
UIImage *blueIcon = [icon maskWithColor:UIColor.blueColor];

回答by aBikis

Swift 4 with customType:

带有 customType 的 Swift 4:

let button = UIButton(frame: aRectHere)
    let buttonImage = UIImage(named: "imageName")
    button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
    button.tintColor = .white

回答by Maciej

For Xamarin.iOS (C#):

对于 Xamarin.iOS (C#):

        UIButton messagesButton = new UIButton(UIButtonType.Custom);
        UIImage icon = UIImage.FromBundle("Images/icon.png");
        messagesButton.SetImage(icon.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
        messagesButton.TintColor = UIColor.White;
        messagesButton.Frame = new RectangleF(0, 0, 25, 25);

回答by Alessandro Ornano

Swift 3:

斯威夫特 3

This solution could be comfortable if you have already setted your image through xCode interface builder. Basically you have one extension to colorize an image:

如果您已经通过 xCode 界面构建器设置了图像,则此解决方案可能会很舒服。基本上你有一个扩展来着色图像:

extension UIImage {
    public func image(withTintColor color: UIColor) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(CGBlendMode.normal)
        let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context.clip(to: rect, mask: self.cgImage!)
        color.setFill()
        context.fill(rect)
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
}

Then , you can prepare this UIButtonextension to colorize the image for a particular state:

然后,您可以准备此UIButton扩展来为特定状态的图像着色:

extension UIButton {
    func imageWith(color:UIColor, for: UIControlState) {
        if let imageForState = self.image(for: state) {
            self.image(for: .normal)?.withRenderingMode(.alwaysTemplate)
            let colorizedImage = imageForState.image(withTintColor: color)
            self.setImage(colorizedImage, for: state)
        }
    }
}

Usage:

用法:

myButton.imageWith(.red, for: .normal)

P.S. (working good also in table cells, you don't need to call setNeedDisplay()method, the change of the color is immediate due to the UIImageextension..

PS(在表格单元格中也很好用,你不需要调用setNeedDisplay()方法,由于UIImage扩展,颜色的变化是立即的..