【问题标题】:How to intersect CAShapeLayers in iOS如何在 iOS 中与 CAShapeLayers 相交
【发布时间】:2018-12-15 15:40:45
【问题描述】:

我有一个加号 (+),目前是蓝色的,但我想让它透明,以便用户可以看到背景。加号层被添加到更大的视图中。将加号图层设置为clear颜色并不能解决问题。

class AddButtonView: UIView {
    ...

    private func setupPlusLayer() {
        let path = UIBezierPath()
        path.move(to: CGPoint(x: plusButton.frame.midX, y: plusButton.frame.midY-20))
        path.addLine(to: CGPoint(x: plusButton.frame.midX, y: plusButton.frame.midY+20))
        path.move(to: CGPoint(x: plusButton.frame.midX-20, y: plusButton.frame.midY))
        path.addLine(to: CGPoint(x: plusButton.frame.midX+20, y: plusButton.frame.midY))
        path.usesEvenOddFillRule = true

        let shapeLayer = CAShapeLayer()
        shapeLayer.fillRule = .evenOdd
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.fillColor = UIColor.blue.cgColor
        shapeLayer.lineWidth = 4

        // Add that `CAShapeLayer` to your view's layer:
        self.layer.addSublayer(shapeLayer)
    }
}

如何使加号透明?

【问题讨论】:

  • 什么是加号按钮层?也许应该是 self.layer add shapelayer
  • @agibson007 谢谢,已编辑

标签: ios swift cashapelayer cgrect


【解决方案1】:

您可以通过以下方式实现:

  1. 创建圈子CAShapeLayer (circleShape);
  2. 创建与circleShape 相同颜色的反转遮罩层 (inverted)。对于这种情况,您需要一个具有完全相同的圆形路径和加号路径的CGMutablePath。另外,别忘了设置inverted.fillRule = .evenOdd
  3. 比你只需要一个透明加号的图层 (plusShape);
  4. 添加circleShape作为视图层的子层;
  5. 设置掩码:circleShape.mask = inverted;
  6. plusShape 添加为视图层的子层。

就是这样!现在你有透明加唱。示例:

【讨论】:

    【解决方案2】:

    尝试使用将 + 设为透明的 .png 图像,它会正常工作,您无需绘制加号。

    【讨论】:

    • 能够以编程方式绘制加号以节省空间并使应用程序能够解决问题,这真是太酷了。
    • 会很酷,但在我看来,如果没有那么好的结果,那就需要大量的工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多