写在前面
所有功能演示
DDGScreenShot 库提供了截取任意图片的功能,
支持手势截图,当然,输入任意的区域也可以,下面看看具体的代码
代码如下:
方法封装
/**
** 用手势截图(截取图片的任意部分)
- imageView --传图片
- bgView --截图背景
*/
public func shotImage(imageView: UIImageView?,bgView: UIView?) -> UIImage? {
if imageView == nil {
return nil
}
//开启一个位图上下文
UIGraphicsBeginImageContextWithOptions((imageView?.bounds.size)!, false, 0.0)
//用贝塞尔绘制
let path = UIBezierPath(rect: (bgView?.frame)!)
//开始截取
path.addClip()
//把ImageView的内容渲染上下文当中.
let imgectx = UIGraphicsGetCurrentContext()
imageView?.layer.render(in: imgectx!)
//从上下文中得到图片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
return newImage
}
异步方法封装
/**
** 异步用手势截图(截取图片的任意部分)
- imageView --传图片
- bgView --截图背景
- parameter completed: 异步完成回调(主线程回调)
*/
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, 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)
//获取起始点
self.setBgView()
if startPan.state == .began {
//获取当前点
self.startPoint = shotPan
} else if startPan.state == .changed {
//获取当前点
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, 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, 200, height: 200)
}
}
### 这样就可以当手势停止就可以得到相应区域的图片
结束语
大功告成,此代码已经上传到githup[DDGScreenShot](https://github.com/dudongge/DDGScreenShot)
[link](https://github.com/dudongge/DDGScreenShot)
当然这只是这个库的功能的一小部分
想看更多功能,可以去github上下载,如果对您有帮助,希望您不吝给个star.
欢迎查看DDGScreenShot