SwiftUI Scale Image Tutorial

In SwiftUI images can be scaled with the scaleEffect modifier. In this tutorial an image is displayed, which can be scaled up and down with a slider. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIScaleImageTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @State var scale: CGFloat = 1.0
    
    var body: some View {
        
        VStack {
            // 2.
            Slider(value: $scale, in: 1.0...10.0, step: 0.1)
                .padding(.bottom, 100)
            // 3.
            Image(systemName: "cloud.rain")
                .scaleEffect(scale)
        }
    }
}
  1. A State property is declared with an initial scale value of 1.0, which is the default size of the image

  2. A Slider is displayed from range 1-10 where each step increments the scale value by 0.1

  3. The scaleEffect modifier scales the image with the current scale value

Go to the preview pane and click the live mode button. Drag the slider to change the scale value of the image.

The source code of the SwiftUIScaleImageTutorial can be downloaded at the ioscreator repository on Github.