简体   繁体   中英

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?

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 .

Note: If you add other UI-elements, they might be hidden under otherView because they are added as subviews of view . To prevent this, you can add them as subview of otherView or reorder the layers. ( 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM