Overlay text on an image in SwiftUI
There are many times when one needs to show text on an image, for example display credits
of the photographer on an image.
SwiftUI makes this incredibly easy to do so with the overlay
modifier.
For this example, we will display an image we got from unsplash.com and then display the name of the photographer who took this image.
We will create a separate view that will display the overlay so we can reuse this if neccessary. We will set the opacity of the view to 60% in our example.
Here is how OverlayTextView
looks with the above setup.
Now we can display this view on top of our backgroundImage
by calling the
overlay
modifier as mentioned earlier. The photographer who took the image
is Grace Gallingam so we will display her name as a credit on our image.
If you want to display the image on the top left we will pass .topLeading
attribute to the
alignment
parameter of the overlay
modifier.