今天做項目的時候需要自定義裁切來自相機圖庫選擇的圖片,找了一圈資料發(fā)現(xiàn)相關的信息甚少。爬了好幾個小時的坑,分享給大家~
開始之前忍不住吐槽一手蘋果,既然系統(tǒng)提供了選取圖片后的裁切功能,讓開發(fā)者傳個CGRect,CGSize進去不應該理所當然嗎?搞得我一開始瘋狂的查水果的 API Reference,最后得出一個無奈的結論。。。寬高定死,你愛用不用:)。。。難道蘋果認為用戶對圖片的需求大小只有那么一種嗎?。。。
其實自定義裁剪器主要就是核心繪圖
1.畫個遮罩出來
IMG_0369.PNG
UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, 0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor)
context?.fill(UIScreen.main.bounds)
context?.addRect(CGRect(x: 0, y: (HEIGHT - selectHeight)/2, width: WIDTH , height: selectHeight))
context?.setBlendMode(.clear)
context?.fillPath()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let selectarea = UIImageView(image: img)
selectarea.frame.origin = CGPoint(x: 0, y: 0)
view.addSubview(selectarea)
2.裁剪圖片(核心部分到這里就結束了)
let rect = UIScreen.main.bounds
// 記錄屏幕縮放比
let scal = UIScreen.main.scale
// 上下文
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
let context = UIGraphicsGetCurrentContext()
UIApplication.shared.keyWindow?.layer.render(in: context!)
// 截全屏,再截圖
guard let img = UIGraphicsGetImageFromCurrentImageContext()?.cgImage,
let result = img.cropping(to: CGRect(x: 0, y: (HEIGHT - selectHeight)/2 * scal, width: self.WIDTH * scal, height: selectHeight * scal)) else{
return nil
}
// 關閉上下文
UIGraphicsEndImageContext()
}
3.定一個協(xié)議來傳值
protocol SwiftyPhotoClipperDelegate {
func didFinishClippingPhoto(image:UIImage)
}
4.忘了一步,關于圖片的縮放,一個 scrollview ,當他的 maximumZoomScale 和 minimumZoomScale 不同并且實現(xiàn) viewForZooming 返回縮放視圖即可。
代碼很簡單,沒什么好貼的,就貼一個定位代碼吧
func scrollViewDidZoom(_ scrollView: UIScrollView) {
//當捏或移動時,需要對center重新定義以達到正確顯示位置
var centerX = scrollView.center.x
var centerY = scrollView.center.y
centerX = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width / 2 : centerX
centerY = scrollView.contentSize.height > scrollView.frame.size.height ?scrollView.contentSize.height / 2 : centerY
self.imgView?.center = CGPoint(x: centerX, y: centerY)
}
5.然后就是使用了,在 didFinishPickingMediaWithInfo 中 跳轉到我們的自定義裁剪器即可
//選擇圖片成功后代理
func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
picker.dismiss(animated: false, completion: {
let clipper = SwiftyPhotoClipper()
clipper.delegate = self
clipper.img = image
self.present(clipper, animated: true, completion: nil)
})
} else{
print("Something went wrong")
}
}
完整demo:https://github.com/KFCFans/SwiftyPhotoClipper
求 Star 啦~么么噠~