我正在尝试制作一个UIButton动画,让它在屏幕上以不同方向随机移动。下面的代码是一种工作。按钮将开始沿随机路径移动,但是,它只是继续在点A和点B之间来回移动。
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationRepeatAutoreverses:YES];
CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);
CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);
CGPoint squarePostion = CGPointMake(x, y);
button.center = squarePostion;
[UIView commitAnimations];
我如何让它在每次改变方向时都保持移动到一个新的随机点,而不是简单地来回移动?
谢谢!
发布于 2011-02-17 20:46:51
试试这个:
-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
// remove:
// [UIView setAnimationRepeatCount:1000];
// [UIView setAnimationRepeatAutoreverses:YES];
CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);
CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);
CGPoint squarePostion = CGPointMake(x, y);
button.center = squarePostion;
// add:
[UIView setAnimationDelegate:self]; // as suggested by @Carl Veazey in a comment
[UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];
[UIView commitAnimations];
}
并且只需要在方法中添加一个计数器(int)来检查它是否被执行了1000次以上,如果想要停止它...
发布于 2021-02-02 18:10:29
制作一个动画的Swift 5示例
@objc func didBecomeActive() {
DispatchQueue.main.async {
self.startAnimationCalm()
}
}
func startAnimation() {
let animatedShadow = UIView(frame: CGRect(origin: CGPoint(x: 10, y: 10), size: CGSize(width: 20, height: 20)))
animatedShadow.clipsToBounds = true
animatedShadow.layer.cornerRadius = 20/2
animatedShadow.backgroundColor = UIColor.green
animatedShadow.layer.borderWidth = 0
self.view.addSubview(animatedShadow)
UIView.animate(withDuration: 5, delay: TimeInterval(0), options: [.repeat, .curveEaseIn], animations: { () -> Void in
let randomX = CGFloat.random(in: 14 ... 200)
let randomY = CGFloat.random(in: 20 ... 600)
animatedShadow.center = CGPoint(x: animatedShadow.frame.origin.x + randomX, y: animatedShadow.frame.origin.y + randomY)
self.view.layoutIfNeeded()
}, completion: { finished in
})
}
https://stackoverflow.com/questions/5034327
复制相似问题