Cesare
Cesare

Reputation: 9419

How to intersect CAShapeLayers in iOS

I have a plus (+) sign that's currently colored in blue but I would like to make it transparent so that the user can see the background. The plus layer is added to a bigger view. Setting the plus layer to clear color doesn't solve the problem.

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

enter image description here

How can I make the plus sign transparent?

Upvotes: 1

Views: 312

Answers (2)

pacification
pacification

Reputation: 6018

You can achieve that, by:

  1. create circle CAShapeLayer (circleShape);
  2. create inverted mask layer (inverted) with same color as circleShape. For this case you need a CGMutablePath with exactly the same circle path and the plus path. Also, don't forget to set inverted.fillRule = .evenOdd;
  3. than you need a layer with transparent plus sign only (plusShape);
  4. add circleShape as a sublayer to view's layer;
  5. setup mask: circleShape.mask = inverted;
  6. add plusShape as a sublayer to view's layer.

That's it! Now you have transparent plus sing. Example:

enter image description here

Upvotes: 1

Omar Masri
Omar Masri

Reputation: 359

Try using a .png image with the + made transparent it will work fine and you will not need to draw the plus.

Upvotes: 1

Related Questions