[英]How do I set a background image in iOS with transparency using Swift?
I'm able to set a patterned background using the following code 我可以使用以下代码设置带图案的背景
view.backgroundColor = UIColor(patternImage: UIImage(named: "imagefilename")!)
It works fine but the image is a png with transparency and I think because of this the transparent areas are coming our as black, is there a way of enabling the transparency so the background colour shows through? 它可以正常工作,但是图像是具有透明性的png,我认为因此透明区域将变成黑色,有没有办法启用透明性以使背景色显示出来?
You see a black background, because there is no view behind the view you are modifying. 您看到黑色的背景,因为您要修改的视图后面没有视图。
If you can't change your image (to make it non-transparent), you could add a subview to your view containing this image: 如果您不能更改图像(使其不透明),则可以向包含该图像的视图添加子视图:
//create a new UIView
let otherView = UIView(frame: view.frame)
otherView.backgroundColor = UIColor(patternImage: UIImage(named: "imagefilename")!)
//now add your new view as subview to the existing one
view.addSubview(otherView)
The transparent parts should now be white by default. 默认情况下,透明部分现在应为白色。 You can change this by modifying
view.backgroundColor
. 您可以通过修改
view.backgroundColor
来更改此view.backgroundColor
。
Note: If you add other UI-elements, they might be hidden under otherView
because they are added as subviews of view
. 注意:如果添加其他UI元素,则它们可能会隐藏在
otherView
下,因为它们是作为view
子视图添加的。 To prevent this, you can add them as subview of otherView
or reorder the layers. 为避免这种情况,您可以将它们添加为
otherView
子视图或对图层重新排序。 ( view.bringSubviewToFront(anotherUIElement)
) (
view.bringSubviewToFront(anotherUIElement)
)
I wrote all the code on the fly, so there might be some syntax errors. 我即时编写了所有代码,因此可能存在一些语法错误。 But the general idea behind this code should work.
但是此代码背后的一般想法应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.