寫(xiě)在前面
DDGScreenShot 庫(kù)提供了截取任意圖片的功能郊艘,
支持手勢(shì)截圖伊磺,當(dāng)然焚辅,輸入任意的區(qū)域也可以浊仆,下面看看具體的代碼
整合成一個(gè)三方庫(kù)记焊,以下只是部分代碼酣溃,詳細(xì)代碼及demo請(qǐng)見(jiàn)瘦穆,github地址https://github.com/dudongge/DDGScreenShot
DDGScreenShot 所有功能演示
image
image
代碼如下:
方法封裝
/**
** 用手勢(shì)截圖(截取圖片的任意部分)
- imageView --傳圖片
- bgView --截圖背景
*/
public func shotImage(imageView: UIImageView?,bgView: UIView?) -> UIImage? {
if imageView == nil {
return nil
}
//開(kāi)啟一個(gè)位圖上下文
UIGraphicsBeginImageContextWithOptions((imageView?.bounds.size)!, false, 0.0)
//用貝塞爾繪制
let path = UIBezierPath(rect: (bgView?.frame)!)
//開(kāi)始截取
path.addClip()
//把ImageView的內(nèi)容渲染上下文當(dāng)中.
let imgectx = UIGraphicsGetCurrentContext()
imageView?.layer.render(in: imgectx!)
//從上下文中得到圖片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
//關(guān)閉上下文
UIGraphicsEndImageContext()
return newImage
}
異步方法封裝
/**
** 異步用手勢(shì)截圖(截取圖片的任意部分)
- imageView --傳圖片
- bgView --截圖背景
- parameter completed: 異步完成回調(diào)(主線(xiàn)程回調(diào))
*/
public func async_shotImage(imageView: UIImageView?,bgView: UIView?,completed:@escaping (UIImage?) -> ()) -> Void {
DispatchQueue.global().async{
let newImage = self.shotImage(imageView: imageView, bgView: bgView)
DispatchQueue.main.async(execute: {
completed(newImage)
})
}
}
使用代碼
imageView = UIImageView()
self.view.addSubview(imageView!)
imageView?.image = UIImage(named: "0")
imageView?.isUserInteractionEnabled = true
imageView?.frame = CGRect(x: 0, y: 0, width: width, height: height)
let pan = UIPanGestureRecognizer(target: self, action: #selector(panTouch(startPan:)))
imageView?.addGestureRecognizer(pan)
func setBgView() {
if bgView == nil {
bgView = UIView()
}
self.view.addSubview(bgView!)
bgView?.backgroundColor = UIColor.black
bgView?.alpha = 0.7
}
@objc func panTouch(startPan: UIPanGestureRecognizer) {
let shotPan = startPan.location(in: imageView)
//獲取起始點(diǎn)
self.setBgView()
if startPan.state == .began {
//獲取當(dāng)前點(diǎn)
self.startPoint = shotPan
} else if startPan.state == .changed {
//獲取當(dāng)前點(diǎn)
let X = startPoint.x
let Y = startPoint.y
let W = shotPan.x - startPoint.x
let H = shotPan.y - startPoint.y
let rect = CGRect(x: X, y: Y, width: W, height: H)
bgView?.frame = rect
} else if startPan.state == .ended {
let newImage = DDGManage.share.shotImage(imageView: imageView, bgView: bgView)
bgView?.removeFromSuperview()
bgView = nil
let imageView1 = UIImageView()
self.view.addSubview(imageView1)
imageView1.image = newImage
imageView1.frame = CGRect(x: 100, y: 200, width: 200, height: 200)
}
}
### 這樣就可以當(dāng)手勢(shì)停止就可以得到相應(yīng)區(qū)域的圖片
結(jié)束語(yǔ)
大功告成,此代碼已經(jīng)上傳到githup[DDGScreenShot](https://github.com/dudongge/DDGScreenShot)
[link](https://github.com/dudongge/DDGScreenShot)
當(dāng)然這只是這個(gè)庫(kù)的功能的一小部分
想看更多功能赊豌,可以去github上下載扛或,如果對(duì)您有幫助,希望您不吝給個(gè)star.
歡迎查看DDGScreenShot