如何在 Swift3 中的捕获图像上添加 UIImage

How to add an UIImage over a captured image in Swift3

在我 post 一些代码和说一些事情之前,我正在使用这个 pod 来拍摄照片和视频:https://github.com/imaginary-cloud/CameraManager 我想做的是简单地获取捕获的图像,在底部放置一个文本(该文本可以通过我已经创建的现有短语数组来选择)并且我想将这两个实体合并为一个新图像,它将显示在一个新的视图控制器中并保存在相机胶卷中,当然是在原始视图之后。我怎样才能做到这一点?谢谢

这是我的捕获照片代码:

let when = DispatchTime.now() + 5
    func capturePicture(){
        _ = cameraManager.addPreviewLayerToView(cameraPreview, newCameraOutputMode: CameraOutputMode.stillImage)

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
            // do stuff x seconds later

            self.cameraManager.capturePictureWithCompletion({ (image, error) -> Void in

                self.cameraPreview.image = image

            })

        }


    }

试试下面的代码片段

UIGraphicsBeginImageContextWithOptions(image!.size, false, 0.0)
// I tought cameraPreview is an imageview
cameraPreview.layer.render(in: UIGraphicsGetCurrentContext()!)
YOUR_UILABEL.layer.render(in: UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let imageData = UIImageJPEGRepresentation(newImage!, 0.9)
let pngImage = UIImage(data: imageData!)
UIGraphicsEndImageContext()

那么你的新图像对象就在 pngImage 上准备好了

协议示例如下

// you can add this protocol to first viewcontroller
protocol ReceiveImageProtocol: class {

    func onReceiveImage(image: UIImage)

}

class FirstViewController: UIViewController, ReceiveImageProtocol {

    ...

    internal func onReceiveImage(image: UIImage) {
        // use merger function for image and label
    }

    internal func openSeconViewController() {
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        secondViewController.imageProtocol = self
        // push or present secondViewController
    }
}

class SecondViewController: UIViewController {

    public weak var imageProtocol: ReceiveImageProtocol!

    // when you capture return back to firstviewcontroller
    // using pop or dismiss
    // and don't forget to call
    // self.imageProtocol.onReceiveImage(image: YOUR_CAPTURED_IMAGE)
}

您可以使用 UIGraphicsBeginImageContextWithOptions 来完成此操作。

UIGraphicsBeginImageContextWithOptions(self.cameraPreview.bounds.size, false, UIScreen.main.scale) self.imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
let captureImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

然后您将获得带有文字的捕获图像。