人要是不兴奋,抗利尿激素都不给力。Talk is cheap,show code,留着给自己以后看。
首先自定义一个view,在创建的时候添加了一个红色视图,放在了上方跟随手拖拽的初始位置,只是通过这个红色的视图更直观的看到拖拽情况。然后创建一个CAShapeLayer,设置渲染填充颜色,路径等拖拽的时候时时更新重绘
private lazy var shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.cyan.cgColor
return shapeLayer
}()
给当前自定义的view添加拖拽手势,根据拖拽的位置绘制shapeLayer。
let tap = UIPanGestureRecognizer.init(target: self, action: #selector(handleTapGestureRecognizer(tap:)))
addGestureRecognizer(tap)
添加一个计时器,在拖拽结束的时候继续重回shapeLayer,计时器默认暂停状态,在手势结束的时候开启
displayLink = CADisplayLink.init(target: self, selector: #selector(caculatePath))
displayLink.add(to: RunLoop.current, forMode: .defaultRunLoopMode)
displayLink.isPaused = true
描绘路径,根据路径绘制shapeLayer,路径从左上角即zero点开始,直线绘制到右上角,接着直线绘制到右下角,然后根据控制点绘制曲线到左下角,下图中黑色是绘制方向,红点是绘制的主要点,绿色是绘制曲线的控制点
func updateShapePath(){
let path = UIBezierPath()
path.move(to: CGPoint.zero)
path.addLine(to: CGPoint.init(x: Device_Width, y: 0))
path.addLine(to: CGPoint.init(x: Device_Width, y: Default_Height))
path.addQuadCurve(to: CGPoint.init(x: 0, y: Default_Height), controlPoint: CGPoint.init(x: controlPoint_X, y: controlPoint_Y))
shapeLayer.path = path.cgPath
}
接着在拖拽界面的时候根据手势进行计算路径,如果处于刚刚松手的状态,即处于果冻效果的动画中,就不用在这里做任何处理,此时会计时器会去计算松手时手势获取最后的触摸点进行绘制。如若处于非动画中,判断手势是否处于移动中,就时刻获取是手势的当前触摸点进行修改控制点的坐标修改控制点的值,绘制shapeLayer。如果处于拖拽取消,拖拽结束,拖拽失败的情况,就开启计时器,控制点的位置重新计算路径绘制shapeLayer。绘制结束后暂停计时器,修改动画状态
// 根据手势计算路径绘制shapeLayer
func handleTapGestureRecognizer(tap: UIPanGestureRecognizer){
if !isAnimateing {
if tap.state == .changed {
let point = tap.translation(in: tap.view)
controlPoint_X = Device_Width / 2 + point.x
controlPoint_Y = point.y + Default_Height
if controlPoint_Y < Default_Height {
controlPoint_Y = Default_Height
}
var frame = visionView.frame
frame.origin.x = controlPoint_X
frame.origin.y = controlPoint_Y
visionView.frame = frame
updateShapePath()
} else if tap.state == .cancelled || tap.state == .ended || tap.state == .failed {
self.displayLink.isPaused = false
self.isAnimateing = true
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
self.visionView.frame = CGRect.init(x: Device_Width / 2 - 1.5, y: Default_Height, width: 3, height: 3)
}, completion: { (finished) in
if finished {
self.displayLink.isPaused = true
self.isAnimateing = false
}
})
}
}
}
// 计时器计算动画状态中的控制点
func caculatePath(){
let layer = visionView.layer.presentation()
self.controlPoint_X = layer?.position.x ?? Device_Width / 2
self.controlPoint_Y = layer?.position.y ?? Default_Height
self.updateShapePath()
}
此时自定义view已经结束,调试的时候也很方便。创建自定义view添加到视图界面展示就好,不要忘记view默认是不可交互的,打开交互才可以。
let jellyView = JellyView.init(frame: self.view.bounds)
jellyView.backgroundColor = .purple
jellyView.isUserInteractionEnabled = true
view.addSubview(jellyView)