在Swift中,我有两个半透明的圆圈,它们都是CAShapeLayer
。由于它们是半透明的,因此它们之间的任何重叠都是可见的,如下所示:
相反,我希望它们在视觉上“合并”在一起。我尝试过的解决方案是使用圆2作为圆1的蒙版,因此可以消除重叠。
该解决方案通常是可行的,但是我在圆圈2的外面得到一条细线:
我的问题:如何摆脱右圆上的细外线?为什么还在那里?
代码如下(Xcode playground can be found here):
private let yPosition: CGFloat = 200
private let circle1Position: CGFloat = 30
private let circle2Position: CGFloat = 150
private let circleDiameter: CGFloat = 200
private var circleRadius: CGFloat { return self.circleDiameter/2.0 }
override func loadView() {
let view = UIView()
view.backgroundColor = .black
self.view = view
let circle1Path = UIBezierPath(
roundedRect: CGRect(
x: circle1Position,
y: yPosition,
width: circleDiameter,
height: circleDiameter),
cornerRadius: self.circleDiameter)
let circle2Path = UIBezierPath(
roundedRect: CGRect(
x: circle2Position,
y: yPosition,
width: circleDiameter,
height: circleDiameter),
cornerRadius: self.circleDiameter)
let circle1Layer = CAShapeLayer()
circle1Layer.path = circle1Path.cgPath
circle1Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
let circle2Layer = CAShapeLayer()
circle2Layer.path = circle2Path.cgPath
circle2Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
self.view.layer.addSublayer(circle1Layer)
self.view.layer.addSublayer(circle2Layer)
//Create a mask from the surrounding rectangle of circle1, and
//then cut out where it overlaps circle2
let maskPath = UIBezierPath(rect: CGRect(x: circle1Position, y: yPosition, width: circleDiameter, height: circleDiameter))
maskPath.append(circle2Path)
maskPath.usesEvenOddFillRule = true
maskPath.lineWidth = 0
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
maskLayer.fillColor = UIColor.black.cgColor
maskLayer.fillRule = kCAFillRuleEvenOdd
circle1Layer.mask = maskLayer
}
最佳答案
如果两个CAShapeLayers具有相同的alpha值,则可以将它们放置在新的父CALayer中,然后设置父代的alpha。
关于ios - 使用CAShapeLayer作为CAShapeLayer的蒙版时的细边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46227172/