これがSwiftUI固有の問題かどうかはわかりません。とにかく、UIViewControllerRepresentableProtocolを使用してSwiftUIビューに実装したUIImagePickerControllerがあります。
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修飾子が適用されないようです。誰かが私のコードで何か問題を見つけたり、解決策を知っていますか?