效果:点击中间的图片按钮会提示打开相机或相册,点击相应照片可以编辑需要显示的内容大小,然后更换刚才图片按钮的图片



import UIKit
class ViewController: UIViewController {
@IBOutlet weak var uiimageButton: UIButton!
@IBAction func btnAction(sender: UIButton) {
let alertC = UIAlertController(title: "选择图像", message: nil, preferredStyle: .ActionSheet)
//相册
let action1 = UIAlertAction(title: "相册", style: .Default) { (_) in
//打开相册
self.openPhotograph()
}
//相机
let action2 = UIAlertAction(title: "相相机", style: .Default) { (_) in
//打开相机
self.openCamera()
}
let action3 = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
alertC.addAction(action1)
alertC.addAction(action2)
alertC.addAction(action3)
self.presentViewController(alertC, animated: true, completion: nil)
}
}
//MARK: - 打开相册
extension ViewController{
//MARK: - 打开相册
func openPhotograph(){
//1.创建图片选择器
let imagePicker = UIImagePickerController()
//2.设置
//.Camera -> 使用相机拍摄
//.PhotoLibrary -> 相册(相机拍摄得到的)
//.SavedPhotosAlbum -> 图册(保存了的图片,范围比相册广)
imagePicker.sourceType = .SavedPhotosAlbum
//3.显示图片选择器
self.presentViewController(imagePicker, animated: true, completion: nil)
//4.设置代理
//遵循
//1.UIImagePickerControllerDelegate
//2.UINavigationControllerDelegate
imagePicker.delegate = self
//5.设置可以编辑
imagePicker.allowsEditing = true
}
//MARK: - 打开相机
func openCamera(){
//1.判断是否有相机
//方法:是否能获得指定资源
let haveCamera = UIImagePickerController.isSourceTypeAvailable(.Camera)
if haveCamera == false{
print("不支持相机")
return
}
//2.创建图片选择器对象
let imagePicker = UIImagePickerController()
//3.设置资源类型为相机
imagePicker.sourceType = .Camera
//4.允许图片编辑
imagePicker.allowsEditing = true
//5.设置代理
imagePicker.delegate = self
//遵循协议同上边一样
//6.显示图片选择器
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
extension ViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
//选中相机或者相册中的一张图片后会自动调用
//参数2:所选中媒体的所有信息列表
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//1.获取选中的图片的原图
//获取字典key的方法
//print(info)
//UIImagePickerControllerOriginalImage -> 被选中的对象的字典key
//UIImagePickerControllerEditedImage -> 编辑之后对象的字典key
//let image1 = info["UIImagePickerControllerOriginalImage"] as! UIImage
//获取编辑后的图片(框住的部分)
let image2 = info["UIImagePickerControllerEditedImage"] as! UIImage
//2.显示在按钮上
uiimageButton.setImage(image2, forState: .Normal)
//3.让图片选择器消失
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
网友评论