如何更改button.imageView
的tintColor
。如果我在UIImageView
中使用与下面相同的渲染模式的相同图像,tintColor
将发生变化,但按钮的图像视图不会发生同样的情况。是因为buttonType吗?
UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[frontButton setImage:[[UIImage imageNamed:FRONT_IMAGE] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
[frontButton.imageView setTintColor:[UIColor redColor]];
[self addSubview:frontButton];
设置按钮类型"系统",然后设置色调。这个解决方案肯定会奏效。请尝试这个
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTintColor:YOUR_COLOR];
[btn setImage:YOUR_Image];
尝试此代码更改按钮内部的色调:
UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:FRONT_IMAGE]];
imageV.image = [imageV.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageV.tintColor = [UIColor redColor];
[frontButton setImage:imageV.image forState:UIControlStateNormal];
Swift 4.0
extension UIImage {
public static func imageWithRenderingModeAlwaysTemplate(named: String) -> UIImage? {
let image = UIImage(named: named)?.withRenderingMode(.alwaysTemplate)
let imageView = UIImageView(image: image)
return imageView.image
}
}
使用
let button = UIButton.setImage(UIImage.imageWithRenderingModeAlwaysTemplate(named: ""), for: .normal)
button.tintColor = .red
您可以执行类似的操作
UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[frontButton setImage:[[UIImage imageNamed:FRONT_IMAGE] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
[frontButton setTintColor:[UIColor redColor]];
[self addSubview:frontButton];
将色调设置为按钮,若图像渲染模式为模板,则它也将获得此色调。
如果您希望按钮的色调不同而图像的色调不同,那么您应该使用一个临时图像视图,并使用渲染模式模板将图像设置为该图像视图,然后将色调设置为该视图,然后从该图像视图将图像设置至按钮。
希望这将有所帮助:)
我找到了答案,我只需要在设置了问题中提到的渲染模式后,将tintColor
给UIButton
,而不是给按钮的imageView
属性。
[button setTintColor:YOUR_COLOR];
Xamarin iOs解决方案:
var image = uiButton.ImageView.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
uiButton.SetImage(image, UIControlState.Normal);
uiButton.TintColor = effect.TintColor.ToUIColor();