iOS 任意切割图片
通过一个镂空的模板选中想要切割的部分, 然后生成图片
必要的属性, 和蒙版 以及要切割的图片. (胖迪)
var imageview = UIImageView.init()
var bezeier : UIBezierPath!
var maskView : UIView!
var circlepath : UIBezierPath!
var shaplayer : CAShapeLayer!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.view.addSubview(imageview)
self.imageview.frame = self.view.bounds
self.imageview.image = UIImage.init(named: "rb02.jpg")
maskView = UIView.init()
maskView.frame = self.view.frame
self.imageview.addSubview(maskView)
maskView.backgroundColor = UIColor.gray
maskView.alpha = 0.8
addrightBtn()
}
生成圆形选中区域的方法 circle()
func cicle() {
self.bezeier = UIBezierPath.init(rect: self.imageview.frame)
self.circlepath = UIBezierPath.init(arcCenter: CGPoint.init(x: 150, y: 300), radius: 100, startAngle: 0, endAngle: CGFloat(Double.pi * 2.0), clockwise: false)
self.bezeier.append(self.circlepath)
shaplayer = CAShapeLayer.init()
shaplayer.path = self.bezeier.cgPath
maskView.layer.mask = shaplayer
}
效果图
重写界面touchmove 方法, 将镂空的圆可以移动.
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
self.bezeier.removeAllPoints()
let p = touches.first?.location(in: self.view)
self.bezeier = UIBezierPath.init(rect: self.imageview.frame)
self.circlepath = UIBezierPath.init(arcCenter: p!, radius: 100, startAngle: 0, endAngle: CGFloat(Double.pi * 2.0), clockwise: false)
self.bezeier.append(self.circlepath)
shaplayer.path = self.bezeier.cgPath
}
生成图片的方法
func addrightBtn() {
let btn:UIBarButtonItem = UIBarButtonItem.init(title: "生成", style: .plain, target: self, action: #selector(btnaction))
self.navigationItem.rightBarButtonItem = btn
}
@objc func btnaction() {
UIGraphicsBeginImageContextWithOptions(self.imageview.frame.size, false, 1)
let bezier = self.circlepath
// let bezier = self.bezeier
bezier?.addClip()
let image = UIImage.init(named: "rb02.jpg")
image?.draw(in: self.imageview.frame)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
self.imageview.image = newImage
UIGraphicsEndImageContext()
}
效果图
重写touchmove 绘制滑动曲线
let p = touches.first?.location(in: self.view)
if self.bezeier == nil {
self.bezeier = UIBezierPath.init()
}
if self.bezeier.isEmpty {
self.bezeier.move(to: p!)
}
if shaplayer == nil {
shaplayer = CAShapeLayer.init()
}
self.bezeier.addLine(to: p!)
shaplayer.path = self.bezeier.cgPath
shaplayer.fillColor = nil
shaplayer.lineWidth = 3
shaplayer.strokeColor = UIColor.red.cgColor
self.imageview.layer.addSublayer(shaplayer)
生成图片的方法, 封闭曲线选择自定的bezier 而不是 那个 circle
@objc func btnaction() {
UIGraphicsBeginImageContextWithOptions(self.imageview.frame.size, false, 1)
/// 拿到圆圈的封闭区域
// let bezier = self.circlepath;
/// 拿到自定义曲线的封闭区域
let bezier = self.bezeier
bezier?.addClip()
let image = UIImage.init(named: "rb02.jpg")
image?.draw(in: self.imageview.frame)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
self.imageview.image = newImage
UIGraphicsEndImageContext()
}
效果图