2017-04-13 26 views
1

我目前正在製作一個swift程序,其中涉及使用操作表從相機或照片庫中選擇圖像的屏幕。這是完全功能,但我希望能夠從選定的圖像中選擇一個方形部分,類似於蘋果的默認應用程序。我怎樣才能實現這個?這裏是我的功能代碼:在swift中用imagepickercontroller裁剪圖像

func chooseImage(_ sender: Any) { 

    let imagePickerController = UIImagePickerController() 
    imagePickerController.delegate = self 

    let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet) 

    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in 

     if UIImagePickerController.isSourceTypeAvailable(.camera) { 
      imagePickerController.sourceType = .camera 
      self.present(imagePickerController, animated: true, completion: nil) 
     }else{ 
      print("Camera not available") 
     } 


    })) 

    actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in 
     imagePickerController.sourceType = .photoLibrary 
     self.present(imagePickerController, animated: true, completion: nil) 
    })) 

    actionSheet.addAction(UIAlertAction(title: "Default", style: .default, handler: { (action:UIAlertAction) in 
     self.avatarImageView.image = UIImage(named: "Avatar.png") 


    })) 

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) 

    self.present(actionSheet, animated: true, completion: nil) 


} 

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage 

    avatarImageView.image = image 

    picker.dismiss(animated: true, completion: nil) 
} 

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 
    picker.dismiss(animated: true, completion: nil) 
} 
// Saves the User singleton object onto the device 
static func saveData() { 
    let savedData = NSKeyedArchiver.archivedData(withRootObject: User.sharedUser) 
    UserDefaults.standard.set(savedData, forKey: "user") 
} 

回答

6

您可以使用默認控件來實現圖像裁剪。

self.imgPicker.allowsEditing = true 

委託方法

//MARK: image picker delegate method 
    //MARK: 
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 

     var image : UIImage! 

     if let img = info[UIImagePickerControllerEditedImage] as? UIImage 
     { 
      image = img 

     } 
     else if let img = info[UIImagePickerControllerOriginalImage] as? UIImage 
     { 
      image = img 
     } 


     picker.dismiss(animated: true,completion: nil) 
} 
+0

這爲我工作 - 好和簡單。 –

+0

完美作品 –

+0

Android作物在iOS上的單行代碼中是痛苦的! – odvan