Is there a way to overlap 2 or more UIViews
with differing background colors and alphas to give the appearance of another color? For example place a red UIView
on top of a blue UIView
to give the appearance of a single magenta UIView
.
问题:
回答1:
On iOS the only blending mode for views if the so-called "source over" mode.
Basically RGB_result = RGB_back * (1 - Alpha_front) + RGB_front * Alpha_front
Thus a red (1, 0, 0) view with 0.5 alpha on top of a blue (0, 0, 1) view will result in dark magenta (0.5, 0, 0.5)
If you need some other blending mode, consider drawing with CoreGraphics (e.g. CGContextSetBlendMode
)
回答2:
You could use the alpha property like so:
UIView *redView = [[UIView alloc] initWithFrame: CGRectMake(0,0,20,20)];
redView.backgroundColor = [UIColor redColor];
UIView *blueView = [[UIView alloc] initWithFrame: CGRectMake(0,0,20,20)];
blueView.backgroundColor = [UIColor blueColor];
blueView.alpha = 0.5;
[redView addSubview: blueView];
Note, this is much easier to achieve in a single view by getting the colour you want manually using the RGB creation method of UIColor:
UIView *magentaView = [[UIView alloc] initWithFrame: CGRectMake(0,0,20,20)];
UIColor *magenta = [UIColor colorWithRed: 1
green: 0
blue: 1
alpha: 1];
magentaView.backgroundColor = magenta;
The RGB values are between 0 and 1, note (not the standard 0 -> 255 range that most would normally be specified with). The alpha value denotes the opacity.
回答3:
This gives a purple view, no problem.
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:self.view.bounds];
view1.backgroundColor = [UIColor colorWithRed:1.f green:0.f blue:0.f alpha:0.5f];
[self.view addSubview:view1];
view1 = [[UIView alloc] initWithFrame:self.view.bounds];
view1.backgroundColor = [UIColor colorWithRed:0.f green:0.f blue:1.f alpha:0.5f];
[self.view addSubview:view1];
}
回答4:
The below method working for me
- (void)viewDidLoad {
[super viewDidLoad];
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeColor);
}