How to save only UIImageView not the whole screen in my photo app. In Swift

人走茶凉 提交于 2019-12-12 04:17:03

问题


My app has a camera section. It takes a photo and then puts a watermark on the photo. However when the photo is saved, the whole screen is saved, not just the UIImageView. I just want the UIImageView to be saved. It's not that but because the menu bar at the button is not that big. I just think it would look better without the menu bar in the picture.

Photo of app just before taking photo:

Photo of how the picture taken is saved:

This is my code below.

import UIKit

class Camera:  UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
    @IBOutlet weak var cameraScreen: UIImageView!
    var screenView: UIImageView!


    @IBAction func Camera(_ sender: AnyObject) {

        if     UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)}}

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!){
        cameraScreen.image = image
        self.dismiss(animated: true, completion: nil);
        screenView = UIImageView()
        screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

        let text = "Java"
        let label = UILabel(frame: CGRect(x: 125, y: 400, width: self.view.frame.width, height: 300))
        label.font = UIFont(name: label.font.fontName, size: 200)

        label.textColor = UIColor.blue
        label.alpha = 0.3
        label.text = text

        self.view.addSubview(screenView)
        self.view.addSubview(label)

        // i tried self, nil, nil

        UIGraphicsBeginImageContext(self.view.frame.size)
        self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)
        let photo = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageWriteToSavedPhotosAlbum(photo!, nil, nil, nil)
    }

    @IBAction func Save(_ sender: AnyObject) {
        let alert = UIAlertController(title: "Image Saved", message: "", preferredStyle: .alert)
        let okay = UIAlertAction(title: "OK.", style: .default, handler: nil)
        alert.addAction(okay)
        present(alert, animated: true, completion: nil)
    }
}

来源:https://stackoverflow.com/questions/40424554/how-to-save-only-uiimageview-not-the-whole-screen-in-my-photo-app-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!