Overlapping UIViews of Differing Color and Alpha

一个人想着一个人 提交于 2020-01-02 13:16:11

问题


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);
}


来源:https://stackoverflow.com/questions/19117072/overlapping-uiviews-of-differing-color-and-alpha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!