在許多的動畫運用中尤其是轉場動畫,很有可能會需要用到對畫面進行截圖。
黄色外框所覆蓋的部分就是我们想要截取的内容,这是预先放上的 captureView (UIView)
captureView = UIView(frame: CGRect(x: screen.midX - 60 , y: 40, width: 200, height: 200))
captureView.layer.borderColor = UIColor.yellow.cgColor
captureView.layer.borderWidth = 2
captureView.backgroundColor = UIColor.black
captureView.alpha = 0.4
view.addSubview(captureView)
點下畫面中的按鈕以後,先拿到整個畫面,然後進行 crop 的動作拿到我們要的圖片,接著在傳給 DetailViewController 就完成了
fileprivate func captureImage() -> UIImage {
// capture HomeViewController's view
UIGraphicsBeginImageContextWithOptions((view.bounds.size), true, 1)
view?.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
// Snapshot
let snapShot = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// crop image
let tempImageRef = snapShot.cgImage!
let croppedImageRef = tempImageRef.cropping(to: captureView.frame)
let croppedImage = UIImage(cgImage: croppedImageRef!, scale: snapShot.scale, orientation: UIImageOrientation.up)
return croppedImage
}