如何使 CALayer 边框 alpha 值与 bgcolor 不同

How to make CALayer border alpha value different with the bgcolor

我有一个 UIView,它有一个 alpha 值为 0.5 且背景色为白色的图层。我需要有一个具有相同白色但 alpha 值为 1 的边框。不幸的是,据我所知,边框的 alpha 值始终与 bgcolor 的相同。所以我的问题是:

  1. 我可以使边框的 alpha 与 bgcolor 不同吗?
  2. 如果我做不到,你有什么建议吗?

试试这个。这应该只更改边框颜色和 alpha。

[self.yourView.layer setBorderColor:[UIColor colorWithRed: 0.0 green: 0.0 blue: 0.0 alpha:1.0].CGColor];当然你可以改变RGB值到你需要的任何值。

Can I make the alpha of the border different with the bgcolor?

是的。你可以这样做:

CALayer * firstLayer = [[CALayer alloc] init];

[firstLayer setFrame:CGRectMake(100, 100, 100, 100)];

firstLayer.borderColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0].CGColor;
firstLayer.borderWidth = 3.0f;
firstLayer.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5].CGColor;

另一种方法是将一个层放在另一个相同大小的层中。为外层提供所需的边框厚度,并确保其不透明度为 100%。第二层应该有分数不透明度:

CALayer * firstLayer = [[CALayer alloc] init];
CALayer * secondLayer = [[CALayer alloc] init];

[firstLayer setFrame:CGRectMake(100, 100, 100, 100)];
[secondLayer setFrame:CGRectMake(0, 0, 100, 100)];
[firstLayer addSublayer:secondLayer];

firstLayer.borderColor = [UIColor redColor].CGColor;
firstLayer.borderWidth = 1.0f;

secondLayer.backgroundColor = [UIColor redColor].CGColor;
secondLayer.opacity = 0.8f;

[self.view.layer addSublayer:firstLayer];

只需使用:

view.layer.borderColor = [[UIColor redColor] colorWithAlphaComponent:0.6].CGColor;
view.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.2];