gpt4 book ai didi

SwiftUI AspectRatio 不适用于来自相机的图像

转载 作者:行者123 更新时间:2023-11-28 05:36:53 24 4
gpt4 key购买 nike

我不确定这是否是 SwiftUI 特定的问题。无论如何,我有一个 UIImagePickerController,我通过使用 UIViewControllerRepresentableProtocol 将其实现到 SwiftUI View 中:

struct ContentView: View {

@State var showCameraView = false
@State var showImagePicker = false
@State var UserImage = Image("user")

var body: some View {
VStack {
UserImage
.resizable()
.frame(width: 200, height: 200)
.scaledToFit()
.background(Color.gray)
.cornerRadius(200)
.clipped()
Button(action: {self.showImagePicker = true}) {
Text("Choose from camera roll")
}
.padding(.top, 10)
}
.sheet(isPresented: $showImagePicker) {
ImagePicker(showImagePicker: self.$showImagePicker, pickedImage: self.$UserImage)
}

}

struct ImagePicker: UIViewControllerRepresentable {

@Binding var showImagePicker: Bool
@Binding var pickedImage: Image

func makeCoordinator() -> ImagePicker.Coordinator {
Coordinator(self)
}

func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let imagePicker = UIImagePickerController()
imagePicker.delegate = context.coordinator
return imagePicker
}

func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
return
}

class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker

init(_ imagePicker: ImagePicker) {
self.parent = imagePicker
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
parent.pickedImage = Image(uiImage: uiImage)
parent.showImagePicker = false
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
parent.showImagePicker = false
}
}

选择设备相机未拍摄的图像时,它可以正常工作。但是,每次我选择由相机本身拍摄的图像时,似乎都没有应用 .aspectRatio 修饰符,因为在这种情况下加载图像的尺寸是扭曲的。有人发现我的代码有问题或知道解决方案吗?

最佳答案

遇到了同样的问题。我使用了@ninjahamster 提出的版本的修改版本,我只是没有调整图像的大小。欢迎任何其他解决方案。

    func resizeImage(image: UIImage) -> UIImage {
let width = image.size.width
let height = image.size.height
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
image.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}

关于SwiftUI AspectRatio 不适用于来自相机的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58356020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com