MM1010
MM1010

Reputation: 573

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?

Upvotes: 0

Views: 4722

Answers (1)

FelixSFD
FelixSFD

Reputation: 6102

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.

Upvotes: 1

Related Questions