Learn Courses My Dashboard

Filling a shape (rectangle) with an image

Does anyone know if it is possible to fill a shape (rectangle or any other) with an image, ie. so that it’s foreground is an image rather than a solid colour?

I have been searching google but no dice so far.

Thanks

Are you trying to do this with SwiftUI or with UIKit?

Sorry I should have said; Swift UI

You can’t fill a shape (a rectangle for example) with an image in SwiftUI. What you can do is overlay an image on the rectangle such that the image only occupies the same space that the rectangle occupies. Though overlaying and image on a rectangle would not be sensible unless you intended to have part of that rectangle visible behind the image (you may have a reason to want to do that… I don’t know).

An image can be resized so that it occupies a specific frame size and in so doing you can set it so that it maintains it’s aspect ratio which will mean that if the rectangle is not the same ratio as the image then the image will be sized to fit within the bounds of the rectangle.

Can’t you just make the .background() your image and make the foreground color .clear?

Ah yes, thinking outside the square. Good point.