팬 제스처 후 velocity를 이용한 포물선 애니메이션
11624 단어 iOSSwiftanimationGestureRecognizer
UIPanGestureRecognizer
에서 손가락을 놓을 때 velocity
를 사용하여 곡선 이동하는 애니메이션을 만듭니다.Swift 4.2
import UIKit
class ViewController: UIViewController {
var animationSample: AnimationSample?
override func viewDidLoad() {
super.viewDidLoad()
animationSample = AnimationSample(view: view)
}
}
class AnimationSample {
let view: UIView
let circle: UIView = {
let diameter: CGFloat = 120
let view = UIView(frame: CGRect(
x: 0,
y: 0,
width: diameter,
height: diameter))
view.layer.cornerRadius = diameter * 0.5
view.backgroundColor = .blue
return view
}()
init(view: UIView) {
self.view = view
view.addSubview(circle)
circle.center = view.center
let pan = UIPanGestureRecognizer(
target: self,
action: #selector(didPan(gesture:)))
circle.addGestureRecognizer(pan)
}
@objc private func didPan(gesture: UIPanGestureRecognizer) {
let location = gesture.location(in: nil)
switch gesture.state {
case .began:
circle.layer.removeAnimation(forKey: "animation")
UIView.animate(withDuration: 0.1) {
self.circle.center = location
}
case .changed:
circle.center = location
case .ended, .failed, .cancelled:
circle.center = location
animate(velocity: gesture.velocity(in: nil))
break
case .possible:
break
}
}
func animate(velocity: CGPoint) {
let speed: CGFloat = 0.5
let startPoint = circle.center
let endPoint = view.center
let controlPoint = CGPoint(
x: startPoint.x + velocity.x * speed,
y: startPoint.y + velocity.y * speed)
let animation = CAKeyframeAnimation(keyPath: "position")
let path = CGMutablePath()
path.move(to: startPoint)
path.addQuadCurve(to: endPoint, control: controlPoint)
animation.path = path
animation.duration = 1.0
animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
CATransaction.begin()
CATransaction.setCompletionBlock {
self.circle.center = endPoint
}
circle.layer.add(animation, forKey: "animation")
CATransaction.commit()
}
}
Reference
이 문제에 관하여(팬 제스처 후 velocity를 이용한 포물선 애니메이션), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ShingoFukuyama/items/0619a2928dbaa160f84a텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)