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
You’re adding opacity to your whole view, add it to your overlay instead:
.overlay(Color.gray.opacity(0.1))
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.Result: