skip to Main Content

I’m trying to set the opacity of an overlay in SwiftUI.
However, I’m only trying to change the opacity of the overlay, and want to keep the opacity of the symbol that is being overlayed. But, when i apply the .opacity() modifier, it changes the opacity of the whole view (both the image and the overlay)

                Image(systemName: "magnifyingglass")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 20, height: 20)
                    .padding(10)
                    .overlay(Color.gray)
                    .opacity(0.1)
                    .clipShape(Circle())

this code produces this view.

as you can see, the entire view is barely visible, and I am trying to only make the gray circle around the search icon opaque, and keep the opacity of the search icon itself.

2

Answers


  1. You’re adding opacity to your whole view, add it to your overlay instead:

    .overlay(Color.gray.opacity(0.1))

    Login or Signup to reply.
  2. Why are you overlaying the gray circle on top of the symbol? Shouldn’t it be the other way around? The order of view modifiers, including .opacity(), are very important in SwiftUI. If you want to only adjust the opacity of the gray circle, you must attach .opacity() before the overlay.

    Color.gray
    .frame(width: 40, height: 40)
    .clipShape(Circle())
    .opacity(0.1) /// apply to the gray circle
    .overlay( /// overlay does not get affected
        Image(systemName: "magnifyingglass")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .padding(10)
    )
    

    Result:

    Opaque symbol on top of translucent gray circle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search