SwiftUI: Можно ли разрешить пользователю масштабировать изображение, выбранное с помощью PHpicker?

У меня есть средство выбора изображений, созданное с помощью PHPicker, и мне было интересно, можно ли позволить пользователю масштабировать выбранное изображение?

Это не весь код, а просто код для makeUIViewController, который, как мне кажется, необходим для решения этой проблемы. Я, конечно, могу предоставить остальную часть кода, если необходимо.

Это то, что я ищу

         func makeUIViewController(context: Context) -> PHPickerViewController {
        var config = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
        config.filter = .images
        config.selectionLimit = 1
        
        let controller = PHPickerViewController(configuration: config)
        controller.delegate = context.coordinator
        return controller
    }
    

1 ответ

можно использовать эту одну строку после выбора изображения с фиксированной высотой и шириной вашего изображения

      Image(room.thumbnailImage)
    .resizable()
    .frame(width: 32.0, height: 32.0)

или здесь я делюсь своей текущей работой с вами функцией оформления заказа и var body: some View

      import SwiftUI
import PhotosUI

struct PhotoPickerDemo: View {
    @State private var isPresented: Bool = false
    @State var pickerResult: [UIImage] = []
    var config: PHPickerConfiguration  {
       var config = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
        config.filter = .images //videos, livePhotos...
        config.selectionLimit = 0 //0 => any, set 1-2-3 for har limit
        return config
    }
    
    var body: some View {
        ScrollView {
            LazyVStack {
                Button("Present Picker") {
                    isPresented.toggle()
                }.sheet(isPresented: $isPresented) {
                    PhotoPicker(configuration: self.config,
                                pickerResult: $pickerResult,
                                isPresented: $isPresented)
                }
                ForEach(pickerResult, id: \.self) { image in
                    Image.init(uiImage: image)
                        .resizable()
                        .frame(width: UIScreen.main.bounds.width, height: 250, alignment: .center)
                        .aspectRatio(contentMode: .fit)
                }
            }
        }
    }
}

struct PhotoPicker: UIViewControllerRepresentable {
    let configuration: PHPickerConfiguration
    @Binding var pickerResult: [UIImage]
    @Binding var isPresented: Bool
    func makeUIViewController(context: Context) -> PHPickerViewController {
        let controller = PHPickerViewController(configuration: configuration)
        controller.delegate = context.coordinator
        return controller
    }
    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    /// PHPickerViewControllerDelegate => Coordinator
    class Coordinator: PHPickerViewControllerDelegate {
        
        private let parent: PhotoPicker
        
        init(_ parent: PhotoPicker) {
            self.parent = parent
        }
        
        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            
            for image in results {
                if image.itemProvider.canLoadObject(ofClass: UIImage.self)  {
                    image.itemProvider.loadObject(ofClass: UIImage.self) { (newImage, error) in
                        if let error = error {
                            print(error.localizedDescription)
                        } else {
                            self.parent.pickerResult.append(newImage as! UIImage)
                        }
                    }
                } else {
                    print("Loaded Assest is not a Image")
                }
            }
            // dissmiss the picker
            parent.isPresented = false
        }
    }
}

struct photoPickerDemo_Previews: PreviewProvider {
    static var previews: some View {
        PhotoPickerDemo()
    }
}

или если вы хотите обрезать через пользовательский интерфейс, например прикрепить изображение

Шаг 1 Используя Xcode 12, перейдите к File -> Swift Packages -> Add PackageЗависимость и введите https://github.com/marshallino16/ImageCropper

Шаг 2

в вашей didFinishPicking метод, в котором вы получаете выбранное изображение, передайте его в этом пакете, используя эти строки

      let ratio = CropperRatio(width: 1, height: 1)//square ratio for crop

ImageCropperView(image: Image(yourSelectedImageHere),cropRect: nil,ratio: ratio).onCropChanged { (newCrop) in
  print(newCrop)//here you will receive cropped image 
}
Другие вопросы по тегам