1

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?

Cesare
  • 9,139
  • 16
  • 78
  • 130

2 Answers2

1

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

Omar Masri
  • 349
  • 1
  • 8
  • It would be really cool to be able to draw the plus programmatically to save space and make the app resolution-proof. – Cesare Dec 15 '18 at 15:46
  • it will be cool, but it's a lot of work whiteout without that great outcome in my opinion. – Omar Masri Dec 15 '18 at 15:47
1

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

pacification
  • 5,838
  • 4
  • 29
  • 51