iPhone - UIView's backgroundColor - using a pn

2019-04-04 06:31发布

问题:

I'm setting the background color of my UIView (which is within a UIViewController) as follows:

myView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"myTransparentBG.png"]];

I've even tried messing with [myView setOpaque:NO]; but the image doesn't appear transparent. It has a black background to it. Am I abel to fix this programmatically? Otherwise, how are we supposed to set a transparent background to our view?

This seems like a question that should have been asked before, but I couldn't find an answer.

回答1:

When using a transparent pattern, after setting the backgroundColor property, you need to set opaque property to NO on both view and its layer. Here's a sample:

UIView* paperView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,700)];
paperView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"paper.png"]];

[paperView.layer setOpaque:NO];
paperView.opaque = NO;


回答2:

I haven't ever actually done this, but here's what I'd try.

Set the UIView's .backgroundColor to [UIColor clearColor]. Then put a UIImageView containing your PNG as the "lowest" item on the UIView's stack of subviews. Make sure the UIImageView's background color is also clear.



回答3:

Use this: myView.backgroundColor = [UIColor clearColor];

This will set it to a transparent background.