SwiftUI - How to crop the original image (using CGImage) after scaling and moving it?

67 Views Asked by At

I've been trying to solve the problem for a long time, but I can't. I will really appreciate your help! Right now I'm struggling with determining the coordinates (Offset) of the first point of the part of the image I'm seeing on the screen.

For example, this code prints the offset after the image has been moved. And I don't understand how to make it so that when the image is scaled, the offset changes accordingly. I mean that if I want to crop a photo from the same place, for example on the left edge, but at different scales, I can't do that here, because the offset coordinates are not the same.

struct ContentView: View {
    @State private var imageScale: CGFloat = 1.0
    @State private var previousScale: CGFloat = 0
    @State private var imageOffset: CGSize = .zero
    @State private var previousOffset: CGSize = .zero

    var body: some View {
        let dragGesture = DragGesture()
            .onChanged { value in
                self.imageOffset.width = value.translation.width + self.previousOffset.width
                self.imageOffset.height = value.translation.height + self.previousOffset.height
            }
            .onEnded { value in
                self.previousOffset = self.imageOffset

                print("Offset: \(imageOffset)")
            }

        let pinchGesture = MagnificationGesture()
            .onChanged { scale in
                imageScale = scale + previousScale
            }
            .onEnded { _ in
                previousScale = imageScale - 1
            }

        Image(systemName: "person.fill")
            .resizable()
            .scaledToFill()
        .scaleEffect(imageScale)
        .offset(imageOffset)
        .gesture(dragGesture)
        .gesture(pinchGesture)
    }
}
0

There are 0 best solutions below