xcode 设置 UIButton 图像并保持透明度

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

Set UIButton image and maintain transparency

xcodeimageuibuttontransparency

提问by Glib

I have a UIButton (set to type "Custom"). If I set the image in Interface Builder, the image is shown properly, with transparency. But if I try to set it programmatically while the App is running (for example, to change the image displayed on the button), the transparency isn't displayed correctly - instead I get a white background to the image.

我有一个 UIButton(设置为“自定义”类型)。如果我在 Interface Builder 中设置图像,图像会正确显示,具有透明度。但是,如果我尝试在应用程序运行时以编程方式设置它(例如,更改按钮上显示的图像),则透明度无法正确显示 - 而是图像的白色背景。

This is how I'm setting the button's image in code:

这就是我在代码中设置按钮图像的方式:

[die1Button setImage:[UIImage imageNamed:die1.dieImage] forState:UIControlStateNormal];

Would hugely appreciate any ideas.

非常感谢任何想法。

采纳答案by Glib

Xcode was remembering the previous version of the images, the ones without transparency - even though I had added the new versions with transparency. I had to do a Product - Clean and now it's all as expected.

Xcode 正在记住图像的先前版本,即没有透明度的图像 - 即使我添加了具有透明度的新版本。我不得不做一个产品 - 清洁,现在一切都如预期的那样。

回答by devsri

The method you are using puts the image on the foreground of the button. I used the following method and it worked

您正在使用的方法将图像放在按钮的前景。我使用了以下方法并且它有效

[die1Button setBackgroundImage:[UIImage imageNamed:@"yourImageName.png"] forState:UIControlStateNormal];

Hope this works for you as well... :)

希望这也适用于你...... :)