41

SwiftUI Scale Image Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/zMZnmyI
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

Bz2QFr7.png!web

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

QF3Ibe3.png!web

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.

Ej63Mfm.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK