【问题标题】:Overlapping UIViews of Differing Color and Alpha不同颜色和 Alpha 的重叠 UIView
【发布时间】:2013-10-07 15:57:55
【问题描述】:
有没有办法将 2 个或更多 UIViews 与不同的背景颜色和 alpha 重叠以呈现另一种颜色的外观?例如,将红色 UIView 放在蓝色 UIView 之上,以呈现单个洋红色 UIView 的外观。
【问题讨论】:
标签:
ios
graphics
uiview
colors
uikit
【解决方案1】:
在 iOS 上,视图的唯一混合模式是所谓的“来源覆盖”模式。
基本上 RGB_result = RGB_back * (1 - Alpha_front) + RGB_front * Alpha_front
因此,在蓝色 (0, 0, 1) 视图之上具有 0.5 alpha 的红色 (1, 0, 0) 视图将导致深洋红色 (0.5, 0, 0.5)
如果您需要其他混合模式,请考虑使用 CoreGraphics 绘图(例如CGContextSetBlendMode)
【解决方案2】:
您可以像这样使用 alpha 属性:
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];
注意,通过使用 UIColor 的 RGB 创建方法手动获取所需的颜色,在单个视图中实现这一点要容易得多:
UIView *magentaView = [[UIView alloc] initWithFrame: CGRectMake(0,0,20,20)];
UIColor *magenta = [UIColor colorWithRed: 1
green: 0
blue: 1
alpha: 1];
magentaView.backgroundColor = magenta;
RGB 值介于 0 和 1 之间,请注意(不是通常指定的标准 0 -> 255 范围)。 alpha 值表示不透明度。
【解决方案3】:
这给出了一个紫色的视图,没问题。
- (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】:
以下方法对我有用
- (void)viewDidLoad {
[super viewDidLoad];
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeColor);
}