2
1

【SwiftUI】PhotosPickerで画像を選択した後、正方形に切り取りできるようにする

Posted at

はじめに

画像を選択した後に画像を切り取りたいことがあると思います。
allowsEditingというフラグをtrueにすることで選択した後に切り取りの画面に遷移させることができます。

実装

import SwiftUI

public struct PhotoPickerView: UIViewControllerRepresentable {
    @Environment(\.dismiss) private var dismiss: DismissAction

    @Binding private var image: UIImage?

    public init(image: Binding<UIImage?>) {
        self._image = image
    }

    public func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    public func makeUIViewController(context: Context) -> UIImagePickerController {
        let uiImagePickerController = UIImagePickerController()
        uiImagePickerController.delegate = context.coordinator
        uiImagePickerController.sourceType = .photoLibrary
        uiImagePickerController.allowsEditing = true
        return uiImagePickerController
    }

    public func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
}

extension PhotoPickerView {
    public class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: PhotoPickerView

        public init(_ parent: PhotoPickerView) {
            self.parent = parent
        }

        public func imagePickerController(
            _ picker: UIImagePickerController,
            didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
        ) {
            if let image = info[.editedImage] as? UIImage {
                parent.image = image
            } else if let image = info[.originalImage] as? UIImage {
                parent.image = image
            }
            parent.dismiss()
        }
    }
}

使い方

import SwiftUI

struct ContentView: View {
    @State private var isPresentedPhotoPickerView = false
    
    @State private var image: UIImage?

    var body: some View {
        VStack {
            Button {
                isPresentedPhotoPickerView = true
            } label: {
                Text("PhotoPicker表示")
            }
            
            if let image {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFit()
                    .frame(width: 300)
            }
        }
        .sheet(isPresented: $isPresentedPhotoPickerView) {
            PhotoPickerView(image: $image)
                .ignoresSafeArea()
        }
    }
}

おわり

公式でサポートされているおかげで簡単に実装ができますね!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1