How to draw images using Image views?

By | September 22, 2024

In SwiftUI we can render images in different ways. SwiftUI can load images from bundle, from system icons, from a UIImage and many more. Among all these are the most common methods that we use.

If you are using Xcode 15 or later, you can load image from application bundle and display it in an image view using built in static properties. Example is shown below.

Image(.cat)

It was introduced in Xcode 15 along with iOS 17, but works just fine back in all older versions of iOS.

For older version of Xcode, like Xcode 14 and earlier, you need to write name of your image like

     Image("cat")
            .resizable()
            .aspectRatio(contentMode: .fit)
    }

.resizable() modifier sets the image resizable

.aspectRatio() modifier sets the aspect ratio of the image so that it will fit the screen asper our need.

You also can create an image view from an existing UIImage. As loading a UIImage using its named initializer returns an optional image, you should either add a default value or use a force unwrap if you’re sure it will exist in your asset catalog:

        Image(uiImage: UIImage(named: "dog")!)
            .resizable()
            .aspectRatio(contentMode: .fit)

If you want to work with Apple’s SF Symbols icon set, you should use the Image(systemName:) initializer, like this:

    var body: some View {
        Image(systemName: "cloud.snow.fill")
            .font(.largeTitle)
    }

Leave a Reply

Your email address will not be published. Required fields are marked *