coiai Logo

This article is an English translation of the original Japanese post. Read the Japanese original →

[SwiftUI] Dynamically Changing an Image's Scale in Canvas

December 17, 2023

Categories: 未分類

All I wanted was to scale an inserted image up or down while keeping its aspect ratio intact. That was the whole goal.

Assumptions

For this post, let's assume we have the following SwiftUI views.

struct CanvasView: View {
    ...
    @State private var image: NSImage? = nil
    ...
}

struct CanvasToSave: View {
    ...
    @Binding var userImage: NSImage?
    ...
}

CanvasView is a view where the user can pick an image, and the chosen image is stored in image. CanvasToSave is a view that draws that image onto a canvas, pulling the image to draw from userImage.

Adding a scale

First, add a new Binding to both CanvasView and CanvasToSave. This lets the user dynamically change the image's scale.

// CanvasView.swift
struct CanvasView: View {
    ...
    @State private var imageScale: CGFloat = 1.0
    ...
}

// CanvasToSave.swift
struct CanvasToSave: View {
    ...
    @Binding var imageScale: CGFloat
    ...
}

Next, add a slider to CanvasView so the user can adjust the image's scale.

// CanvasView.swift
struct CanvasView: View {
    ...
    var body: some View {
        ...
        Form {
            ...
            Section("Image Scale") {
                Slider(value: $imageScale, in: 0.1...2.0, step: 0.1)
            }
            ...
        }
    }
}

Finally, apply the scale when CanvasToSave draws the image.

// CanvasToSave.swift
struct CanvasToSave: View {
    ...
    var body: some View {
        Canvas { context, size in
            ...
            if let img = userImage {
                let userSelectImage = Image(nsImage: img)
                let scaledSize = CGSize(width: img.size.width * imageScale, height: img.size.height * imageScale)
                context.draw(userSelectImage, in: CGRect(x: midPoint.x - scaledSize.width / 2, y: midPoint.y - scaledSize.height / 2, width: scaledSize.width, height: scaledSize.height))
                context.blendMode = GraphicsContext.BlendMode.softLight
            }
        }
    }
}

With these changes in place, the user can dynamically adjust the image's scale using the slider, and that scale is reflected in userSelectImage within CanvasToSave.