Search code examples
iosswiftuisf-symbols

Inverted mask swiftui with system image


I am trying to cut out a sf symbol from a circle shape in swiftUI.

I currently have the following code:

Circle()
   .fill(Color.white)
   .frame(width: 50, height: 50)
   .mask(
       Image(systemName: "play.fill")
           .font(.system(size: 24))
           .foregroundColor(Color.black)
           .frame(width: 50, height: 50)
   )

Which generates:

enter image description here

However, what I want is to invert the effect of the mask: The symbol is cut out of the circle as in the image below:

enter image description here

Note that the actual background is not red as in the image but will be a user uploaded image, so setting the symbol foregroundColor to red is not possible.

Is there any way to invert the mask of the symbol/image such that the circle has a hole in it with the shape of the image?


Solution

  • This answer by Vlad Lego works when applied here.

    You create your mask using .black for the parts you want cut out, and .white for the parts you want preserved.

    (assuming the background is red, this is what it would look like)

    enter image description here

    Rectangle()
      .foregroundColor(Color.white)
      .mask(
        ZStack {
          Circle()
            .fill(Color.white)
            .frame(width: 50, height: 50)
          Image(systemName: "play.fill")
            .font(.system(size: 24))
            .foregroundColor(Color.black)
        }
          .compositingGroup()
          .luminanceToAlpha()
      )