2016-09-22 101 views
0

我可以使用下面的代码如何使用Swift在iOS中设置背景图片?

view.backgroundColor = UIColor(patternImage: UIImage(named: "imagefilename")!) 

它工作正常,设置一个背景图案,但图像是用透明PNG格式,我想因为这个透明区域的来了我们黑色,有一种启用透明度的方式,以便背景颜色可以通过?

+0

你确定,你正在修改的背后有另一种观点吗? – FelixSFD

+0

这是一个很好的观点,所以这会创建一个新视图并设置背景图片的情况。 – FullerPrime

+0

是的。那么你甚至可以设置图像的透明部分的颜色 – FelixSFD

回答

1

您会看到黑色背景,因为您正在修改的视图背后没有视图。

如果你不能改变你的形象(以使其不透明),你可以一个子视图添加到包含此图片的观点:

//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来更改此设置。

注:如果添加其他UI元素,他们可能会被otherView下,因为它们被添加作为view子视图隐藏。为了防止这种情况,您可以将它们添加为otherView的子视图或重新排序图层。 (view.bringSubviewToFront(anotherUIElement)


我写在飞行的所有代码,所以可能有一些语法错误。但是这个代码背后的一般理念应该能够工作。

+0

谢谢。 – FullerPrime