[英]How do I set a background image in iOS with transparency using Swift?
我可以使用以下代码设置带图案的背景
view.backgroundColor = UIColor(patternImage: UIImage(named: "imagefilename")!)
它可以正常工作,但是图像是具有透明性的png,我认为因此透明区域将变成黑色,有没有办法启用透明性以使背景色显示出来?
您看到黑色的背景,因为您要修改的视图后面没有视图。
如果您不能更改图像(使其不透明),则可以向包含该图像的视图添加子视图:
//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)
默认情况下,透明部分现在应为白色。 您可以通过修改view.backgroundColor
来更改此view.backgroundColor
。
注意:如果添加其他UI元素,则它们可能会隐藏在otherView
下,因为它们是作为view
子视图添加的。 为避免这种情况,您可以将它们添加为otherView
子视图或对图层重新排序。 ( view.bringSubviewToFront(anotherUIElement)
)
我即时编写了所有代码,因此可能存在一些语法错误。 但是此代码背后的一般想法应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.