2016-07-17 2 views
2

В коде Swift, как я могу начать и анимировать UIView так, чтобы он двигался по круговому пути, а затем довел его до конца изящно? Можно ли достичь этого, используя анимацию CGAffineTransform?Как сделать анимацию UIView по круговой траектории?

Я подготовил GIF ниже, показывая тип анимации, которую я пытаюсь достичь.

enter image description here

ответ

14

обновление: Обновление кода Swift 4. Там нет никакой разницы между Swift 3 и 4 Swift для фрагмента кода ниже.

Использовать UIBezierPath и CAKeyFrameAnimation.

Вот код:

//The code is within viewDidLoad method 
let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true) 

let animation = CAKeyframeAnimation(keyPath: "position") 
animation.duration = 1 
animation.repeatCount = MAXFLOAT 
animation.path = circlePath.cgPath 

let squareView = UIView() 
//whatever the value of origin for squareView will not affect the animation 
squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) 
squareView.backgroundColor = .lightGray 
view.addSubview(squareView) 
// You can also pass any unique string value for key 
squareView.layer.add(animation, forKey: nil) 

// circleLayer is only used to locate the circle animation path 
let circleLayer = CAShapeLayer() 
circleLayer.path = circlePath.cgPath 
circleLayer.strokeColor = UIColor.black.cgColor 
circleLayer.fillColor = UIColor.clear.cgColor 
view.layer.addSublayer(circleLayer) 

Вот захват:

enter image description here

Кроме того, вы можете установить anchorPoint свойство squareView.layer, чтобы сделать вид не живой якорь в его центре , Значение по умолчанию anchorPoint равно (0,5, 0,5), что означает центральную точку.

+0

Очень круто. Большое спасибо! – user4806509

Смежные вопросы