图片剪裁选择框 LCResizableView

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

Demo地址

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

效果

LCResizableView

如何引用

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

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<UITouch>, 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<UITouch>, 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<UITouch>, with event: UIEvent?) {
    delegate?.resizableViewEndEditing()
}

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

总结

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

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

联系我

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,222评论 4 61
  • 刘宋沈攸之自认为才略过人,自从宋明帝去世,他镇守夏口以来,一直暗中准备,有夺取政权的野心。等到调任荆州,临走时把郢...
    寒七琪阅读 3,980评论 0 4
  • 自从看了《写作禅》,写作对于我,渐成随时把玩的工具,任随情绪、思绪在指尖流淌。 兴奋同于愤怒,都是一种情绪的浪费。...
    _德成阅读 1,209评论 0 4