UIButton图像颜色渐变

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

你能否发布你想要使用的图片以及期望结果的图片? - Pratyusha Terli
这个做法与界面构建器中的操作相同。 - Chuy47
22个回答

5

如果您在使用 iOS 15 并且正在使用新的 UIButton.Configuration API,则可能需要通过 imageColorTransformer 进行操作。

效果如下:

configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in .green }

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

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

// Usage:
configuration = configuration.imageColor(.green)

和其他答案一样,图像本身必须在Xcode资源的“Render As - Template Image”中,或者在代码中使用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
}

而这本身必须从 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
}

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

非常感谢!现在的正确答案。 - Fattie
1
这个答案应该排到最前面。特别是关于“渲染为-模板图像”的细节让我感到困惑。 - Jonny

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

如果您通过UIColor(r:g:b:alpha:)设置UIButton.tintColor,请记得将值除以255。RGB值应该在0和1之间。


3
如果您想手动遮罩您的图像,这里是更新后适用于视网膜屏幕的代码。
- (UIImage *)maskWithColor:(UIColor *)color
{
    CGImageRef maskImage = self.CGImage;
    CGFloat width = self.size.width * self.scale;
    CGFloat height = self.size.height * self.scale;
    CGRect bounds = CGRectMake(0,0,width,height);

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

    CGImageRef cImage = CGBitmapContextCreateImage(bitmapContext);
    UIImage *coloredImage = [UIImage imageWithCGImage:cImage scale:self.scale orientation:self.imageOrientation];

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

    return coloredImage;
}

2

Swift 3.0

    let image = UIImage(named:"NoConnection")!

 warningButton = UIButton(type: .system)        
    warningButton.setImage(image, for: .normal)
    warningButton.tintColor = UIColor.lightText
    warningButton.frame = CGRect(origin: CGPoint(x:-100,y:0), size: CGSize(width: 59, height: 56))

    self.addSubview(warningButton)

2
为了将按钮上的图像(箭头图标)设置为白色,我们使用以下代码:
let imageOnButton = UIImage(named: "navForwardArrow")?.imageWithColor(color: UIColor.white)
button.setImage(imageOnButton, for: .normal)

已知问题:当按钮被按下时,图标失去了白色。
截图:enter image description here

2

你应该尝试一下

在设置框架之后

NSArray *arr10 =[NSArray arrayWithObjects:btn1,btn2,nil];
for(UIButton *btn10 in arr10)
{
CAGradientLayer *btnGradient2 = [CAGradientLayer layer];
btnGradient2.frame = btn10.bounds;

btnGradient2.colors = [NSArray arrayWithObjects:
                       (id)[[UIColor colorWithRed:151.0/255.0f green:206.0/255.5 blue:99.0/255.0 alpha:1] CGColor],
                       (id)[[UIColor colorWithRed:126.0/255.0f green:192.0/255.5 blue:65.0/255.0 alpha:1]CGColor],
                       nil];
[btn10.layer insertSublayer:btnGradient2 atIndex:0];

}

1
更改按钮图像或图像视图的色调颜色 Swift:
btn.imageView?.image = btn.imageView?.image?.withRenderingMode(.alwaysTemplate)

btn.imageView?.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

1

如何在 Swift 中更改按钮图像或图像视图的色调:

let image = UIImage(named: "map")
mapButton.setImage(image!.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
mapButton.tintColor = UIColor.black

0

以上方法都对我无效,因为点击后色调被清除了。我不得不使用以下方法:

button.setImageTintColor(Palette.darkGray(), for: UIControlState())

0

我在高亮状态下遇到了图像掩蔽问题。我不想让它发生。如果你有同样的问题,请看一下:adjustsImageWhenHighlighted = false


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接