将相机/照片库中的图像保存到要在UICollectionView中显示的数组中,可以通过以下步骤实现:
以下是一个示例代码,演示了如何将相机/照片库中的图像保存到数组中:
import UIKit
import AVFoundation
import Photos
class ViewController: UIViewController, AVCapturePhotoCaptureDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imageArray: [UIImage] = []
// 拍摄照片
func capturePhoto() {
let captureSession = AVCaptureSession()
guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(input)
let photoOutput = AVCapturePhotoOutput()
captureSession.addOutput(photoOutput)
captureSession.startRunning()
let settings = AVCapturePhotoSettings()
photoOutput.capturePhoto(with: settings, delegate: self)
} catch {
print(error)
}
}
// AVCapturePhotoCaptureDelegate方法,拍摄照片完成后调用
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) {
imageArray.append(image)
}
}
// 选择照片
func selectPhoto() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
// UIImagePickerControllerDelegate方法,选择照片完成后调用
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
imageArray.append(image)
}
picker.dismiss(animated: true, completion: nil)
}
// 在UICollectionView中显示图像
// ...
}
这是一个简单的示例代码,演示了如何将相机/照片库中的图像保存到数组中。你可以根据自己的需求进行修改和扩展,例如在UICollectionView中显示图像等。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云