问题
I am creating a UIView containing some text that partially covers a UIImageView. I want the user to be able to read the text and still maintain a perspective on the image underneath. I have tried setting the background color to [UIColor clearColor], but then the background is totally transparent and it is hard to read the text depending upon the image colors.
If I lower the view.alpha=0.5 the whole view including the text is partially transparent. What I'd like is to maintain the text and reduce the transparency of the background partially, allowing the image to show through.
回答1:
I think what you mean is you want the backgroundColor of your UIView to be semi transparent? If you want white/transparent use this:
myView.backgroundColor = [UIColor colorWithWhite:myWhiteFloat alpha:myAlphaFloat];
else if you want it to be another color use the general UIColor method: +colorWithRed:green:blue:alpha:
回答2:
For those who have their view in a storyboard or .xib, you simply do it in interface builder by selecting the option "Clear Color" for the Background of the view in the Utilities Pane (the pane on the right). "Clear Color" will give the view a completely transparent background.
If you need a background colour that is partially transparent, select the desired background colour with the colour picker and use the Opacity slider at the bottom to set the transparency.
回答3:
This will work.
myView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7f];
回答4:
Eventually you already have a color so you could use .colorWithAlphaComponent
like this:
let exampleColor = UIColor.blackColor()
overlayView.backgroundColor = exampleColor.colorWithAlphaComponent(0.8)
回答5:
I believe you should use:
myView.alpha = myAlphaFloat;
myView.opaque = NO;
回答6:
For Xamarin C#, at this time, the visual storyboard does not have the "opacity" slider of Xcode's storyboard mentioned by Bocaxica.
If you set BackgroundColor
for View nameOfView
in storyboard, then in your view controller's ViewDidLoad
, add this line to set alpha:
nameOfView.BackgroundColor = nameOfView.BackgroundColor.ColorWithAlpha( 0.7f ); // A value between 0 and 1.
回答7:
Swift 3+
white half transparent:
view.backgroundColor = UIColor(white: 1, alpha: 0.5)
or black half transparent:
view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
回答8:
For Swift 4+ :
Black translucent view:
view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
来源:https://stackoverflow.com/questions/6655093/how-do-you-create-a-semi-transparent-background-for-a-uiview