Inverted mask swiftui with system image

倾然丶 夕夏残阳落幕 提交于 2020-06-13 07:04:05

问题


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:

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:

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?


回答1:


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)

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



回答2:


You may use another image:

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


来源:https://stackoverflow.com/questions/60192357/inverted-mask-swiftui-with-system-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!