图片剪裁选择框 LCResizableView

最近遇到裁剪图片的需求,要求选择图片的某一区域进行剪裁,要在图片上呈现选择框来选择区域,这里选择自己开发一款 Swift 的选择框,此为文章由来。

Demo地址

项目demo已经上传到Git, 地址:LCResizableView(点我点我)

效果

图片剪裁选择框 LCResizableView_第1张图片
LCResizableView

如何引用

直接将 LCResizableView 文件夹下的文件拉进项目中即可

图片剪裁选择框 LCResizableView_第2张图片
LCResizableView

如何使用

LCResizableView 的使用非常简单,只需两行代码

let resiable = LCResizableView.init(frame: CGRect.init(x: 50, y: 50, width: 150, height: 150))
imageView.addSubview(resiable)

另外如果要监测选择框的状态,需实现协议 LCResizableViewDelegate

func resizableViewBeginEditing()
func resizableViewEndEditing()
func resizableViewFrameChanged(rect: CGRect)

更改选择框风格

针对选择框的风格这里专门封装成了一个 view 类,可在nib 或 用代码修改成自己需要的样式


LCResizableLayer

开发思路

①首先检测视图 Touch Begin ,确认 Touch 在视图的哪个区域(我把视图按照九宫格分为了九个区域),然后记录开始点击的位置。

enum ResizableViewArea {//响应区分为九大区域
    case upLeft
    case left
    case downLeft
    case down
    case downRight
    case right
    case upRight
    case up
    case center
}

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
    let touch = touches.first
    let touchPoint = touch?.location(in: self)
    guard touchPoint != nil else {
        return
    }
    
    delegate?.resizableViewBeginEditing()
    
    touchArea = checkPointInArea(point: touchPoint!)
    if touchArea == .center {
        startPoint = touch?.location(in: self)
    }else{
        startPoint = touch?.location(in: self.superview)
    }
}

② 然后检测 Touch Move , 根据不同的区域做出相应的 Frame 变换。

override func touchesMoved(_ touches: Set, with event: UIEvent?) {
    if touchArea == .center {
        let touch = touches.first
        let movePoint = touch?.location(in: self)
        guard movePoint != nil else {
            return
        }
        //只做平移
        translate(movePoint: movePoint!)
    }else{
        let touch = touches.first
        let movePoint = touch?.location(in: self.superview)
        guard movePoint != nil else {
            return
        }
        resizable(movePoint: movePoint!)
    }
    
    delegate?.resizableViewFrameChanged(rect: self.frame)
}

③最后通过delegate 传出各种状态

override func touchesEnded(_ touches: Set, with event: UIEvent?) {
    delegate?.resizableViewEndEditing()
}

override func touchesCancelled(_ touches: Set, with event: UIEvent?) {
    delegate?.resizableViewEndEditing()
}

总结

思路很简单,实现也不复杂,需要注意的就是移动到边界的时候要做边界保护处理。

有兴趣的同学可以下载看一看 :LCResizableView(点我点我)

联系我

有什么问题或意见可以联系我,相互交流进步。 —— LC.West

你可能感兴趣的:(图片剪裁选择框 LCResizableView)