我有一个例程,允许用户从他们的照片库中选择图像。 然后我希望能够通过捏合手势缩放图像。我有那个工作:
struct ContentView: View {
@State private var selected : PhotosPickerItem?
@State private var picture : UIImage?
@GestureState private var magnification : CGFloat = 1
@State private var zoom : CGFloat = 1
var body: some View {
NavigationStack {
ScrollView([.vertical, .horizontal]) {
VStack {
Image(uiImage: picture ?? UIImage(named: "nopicture")!)
.resizable()
.scaledToFit()
.scaleEffect(getCurrentZoom(magnification: magnification))
.gesture(MagnificationGesture()
.updating($magnification) { value, state, transaction in
state = value
}
.onEnded { value in
zoom = getCurrentZoom(magnification: value)
})
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
PhotosPicker(selection: $selected, matching: .images, photoLibrary: .shared()) { Text("Select a Photo") }
}
}
.onChange(of: selected) { item in
Task(priority: .background) {
if let data = try? await item?.loadTransferable(type: Data.self) {
picture = UIImage(data: data)
}
}
}
}
}
func getCurrentZoom(magnification : CGFloat) -> CGFloat {
let minZoom : CGFloat = 1
let maxZoom : CGFloat = 4
var current = zoom * magnification
current = max(min(current, maxZoom), minZoom)
return current
}
}
但是我现在正试图滚动放大的图像。 我试图将它放入 ScrollView 但是当图像被加载时它已经放大非常大并且我无法缩小它(尽管它仍然可以按比例放大。) 这是我正在尝试的代码,ScrollView 包含包含 UIImage 的 VStack:
struct ContentView: View {
@State private var selected : PhotosPickerItem?
@State private var picture : UIImage?
@GestureState private var magnification : CGFloat = 1
@State private var zoom : CGFloat = 1
var body: some View {
NavigationStack {
VStack {
ScrollView([.vertical, .horizontal]) {
Image(uiImage: picture ?? UIImage(named: "nopicture")!)
.resizable()
.scaledToFit()
.scaleEffect(getCurrentZoom(magnification: magnification))
.gesture(MagnificationGesture()
.updating($magnification) { value, state, transaction in
state = value
}
.onEnded { value in
zoom = getCurrentZoom(magnification: value)
})
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
PhotosPicker(selection: $selected, matching: .images, photoLibrary: .shared()) { Text("Select a Photo") }
}
}
.onChange(of: selected) { item in
Task(priority: .background) {
if let data = try? await item?.loadTransferable(type: Data.self) {
picture = UIImage(data: data)
}
}
}
}
}
func getCurrentZoom(magnification : CGFloat) -> CGFloat {
let minZoom : CGFloat = 1
let maxZoom : CGFloat = 4
var current = zoom * magnification
current = max(min(current, maxZoom), minZoom)
return current
}
}
谢谢