色彩UIButton图像

Log*_*ire 265 iphone uibutton uisegmentedcontrol ios ios7

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

Ric*_*tos 578

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

Objective-C的

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[button setImage:image forState:UIControlStateNormal]; 
button.tintColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)

迅速

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

  • 只记得在每个@hashier的xcassets中为图像设置图像渲染模式 (30认同)
  • 创建UIButtonTypeSystem类型的UIButton将自动遵循您设置的tintColor. (21认同)
  • 我认为最好使用button.imageView.tintColor (13认同)
  • 如果你的'tintColor`太暗,请确保`adjustsImageWhenHighlighted`为NO.(或者在IB中:未选中"突出显示的调整图像".) (4认同)
  • @ M.Othman仅在我使用button.tintColor而不是button.imageview.tintColor时为我工作 (2认同)

has*_*ier 216

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

在此输入图像描述

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

  • @AxelGuilmin不是真的.您的图像可以是您想要的任何颜色和透明.任何不同于透明**的颜色都将转换为通用颜色**,然后默认情况下将使用黑色进行着色. (6认同)

auc*_*uco 81

自定义按钮以各自的图像颜色显示.在故事板(或UIButtonTypeSystem代码中)中将按钮类型设置为"系统" ,将使用默认的色调颜色呈现按钮的图像.

按钮类型系统渲染图标着色

(在iOS9上测试,Xcode 7.3)

  • 使用此处建议的alwaysTemplate和tintColor方法可以避免这种情况.凭借.system按钮的优势,您可以通过点击触摸来获得颜色变化. (2认同)

小智 39

您必须将图像渲染模式设置为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()
Run Code Online (Sandbox Code Playgroud)


Ilk*_*aci 25

如果您有一个带背景图像的自定义按钮.您可以设置按钮的色调颜色并覆盖图像.

在资源中,选择要设置色调颜色的按钮背景.

在图像集的属性检查器中,值呈现为"模板图像"

在此输入图像描述

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


hen*_*dmg 17

在Swift中你可以这样做:

var exampleImage = UIImage(named: "ExampleImage.png")?.imageWithRenderingMode(.AlwaysTemplate)
Run Code Online (Sandbox Code Playgroud)

然后在你的viewDidLoad中

exampleButtonOutlet.setImage(exampleImage, forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

并修改颜色

exampleButtonOutlet.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) //your color
Run Code Online (Sandbox Code Playgroud)

编辑Xcode 8 现在你也可以只将.xcassets中图像的渲染模式转换为模板图像,然后你就不需要再在其中专门声明它var exampleImage了.


Kir*_*odd 14

不确定你想要什么,但这个类别方法将掩盖具有指定颜色的UIImage,因此您可以拥有单个图像并将其颜色更改为您想要的任何颜色.

ImageUtils.h

- (UIImage *) maskWithColor:(UIColor *)color;
Run Code Online (Sandbox Code Playgroud)

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;    
}
Run Code Online (Sandbox Code Playgroud)

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

#import "ImageUtils.h"

...

UIImage *icon = [UIImage imageNamed:ICON_IMAGE];

UIImage *redIcon = [icon maskWithColor:UIColor.redColor];
UIImage *blueIcon = [icon maskWithColor:UIColor.blueColor];
Run Code Online (Sandbox Code Playgroud)

  • 很好,但需要调整Retina图形......当我在Retina图像上运行它时,它会返回一个非视网膜图像. (4认同)
  • 在`CGBitmapContextCreate`上使用`kCGBitmapAlphaInfoMask&kCGImageAlphaPremultipliedLast` (3认同)

aBi*_*kis 8

带有customType的Swift 4:

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


Nik*_*iev 6

如果您在 iOS 15 之后到达这里并且正在使用新的UIButton.ConfigurationAPI,那么您可能需要通过imageColorTransformer.

看起来像这样:

configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in .green }
Run Code Online (Sandbox Code Playgroud)

为了方便起见,您可以创建一个扩展:

extension UIButton.Configuration {
    func imageColor(_ color: UIColor) -> UIButton.Configuration {
        var configuration = self
        configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in color }
        return configuration
    }
}

// Usage:
configuration = configuration.imageColor(.green)
Run Code Online (Sandbox Code Playgroud)

与其他答案一样,图像本身必须是 Xcode 资产中或代码中的“渲染为 - 模板图像”image.withRenderingMode(.alwaysTemplate)


额外提示
如果您希望在按钮突出显示时改变图像颜色怎么办?那么你的配置扩展可以如下所示:

func imageColor(whenNormal: UIColor,
                whenHighlighted: UIColor,
                isHighlighted: Bool) -> UIButton.Configuration {
    var configuration = self
    configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in
        isHighlighted ? whenHighlighted : whenNormal
    }
    return configuration
}
Run Code Online (Sandbox Code Playgroud)

这本身必须从configurationUpdateHandler上下文中调用,如下所示:

someButton.configurationUpdateHandler = { button in
    guard var configuration = button.configuration else {  return }
    configuration.image = UIImage(named: "some_image")
    configuration = configuration.imageColor(whenNormal: .green,
                                             whenHighlighted: .green.withAlphaComponent(0.7),
                                             isHighlighted: button.isHighlighted)
    button.configuration = configuration
}
Run Code Online (Sandbox Code Playgroud)

请注意,configurationUpdateHandler您实际上还可以根据按钮状态定义不同的图像。


Mac*_*wia 5

对于 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);
Run Code Online (Sandbox Code Playgroud)


Ale*_*ano 5

斯威夫特3

如果您已经通过 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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以准备此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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

myButton.imageWith(.red, for: .normal)
Run Code Online (Sandbox Code Playgroud)

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


Far*_*ruk 5

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

如果您设置UIButton.tintColorUIColor(r:g:b:alpha:),请记住将值除以255。这些 RGB 值应介于 0 和 1 之间。