我正在从它的中心旋转NSImageView,它正在完美地工作,但是当我开始动画时,NSImageView从它的位置跳到随机位置。我不知道为什么会这样。请帮忙。
我正在详细说明我是如何做到这一切的。另外,我提供了一个Github链接,以便您可以根据需要运行它。
代码:
// on button press animation will be started
-(void)buttonPressed:(id)sender{
// setting the anchor point of the view
_img.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
// calling the animation function
[self startRefreshAnimation];
}
// in order to repeate the animation
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
[self startRefreshAnimation];
}
// the function that will handel all the animation stuff
-(void)startRefreshAnimation {
CABasicAnimation *anim2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
NSNumber* toValue = [NSNumber numberWithFloat:0 * (M_PI / 180.0f)];
NSNumber* fromValue = [NSNumber numberWithFloat:(360.0f) * (M_PI / 180.0f)];
anim2.fromValue = toValue;
anim2.toValue = fromValue;
anim2.duration = 1.0f;
anim2.delegate = self;
[_img.layer addAnimation:anim2 forKey:@"transform"];
}
答案 0 :(得分:3)
对于我需要的动画任务,代码看起来很好。只需移动anchorPoint行,如下所示:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
_img.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
}
编辑:基本上,图层的位置是根据图层的anchorPoint的位置指定的。设置图层的位置时,您将在其超层图层的坐标系中设置图层中心的位置。因为位置是相对于图层的anchorPoint,所以在保持相同位置的同时更改该anchorPoint会移动图层。因此,您必须在渲染子视图之前设置anchorPoint。
此外,对于无限重复,您可以通过使用此属性来避免编写 animationDidStop 方法:
anim2.repeatCount = HUGE_VALF;
答案 1 :(得分:2)
您需要在图像视图上设置图层的位置。在buttonPressed方法中添加:
//Position of the imgView
CGRect frame = _img.layer.frame;
float xCoord = frame.origin.x + frame.size.width;
float yCoord = frame.origin.y + frame.size.height;
CGPoint myPoint = CGPointMake(xCoord, yCoord);
_img.layer.position = myPoint;
[self startRefreshAnimation]
这样,您可以在.xib中移动imageView,动画将发生正确的位置。
编辑:@Nishant的解决方案非常漂亮..
答案 2 :(得分:2)
设置图层的锚点,使其围绕正确的中心旋转,然后立即重新定位以考虑新的锚点(否则会改变其位置):
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.toValue = CGFloat(-M_PI * 2.0)
rotateAnimation.duration = 1.0
viewToRotate.layer?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
viewToRotate.layer?.position = viewToRotate.center
viewToRotate.layer?.addAnimation(rotateAnimation, forKey: nil)
使用...
extension NSView {
var center: CGPoint {
get {
return CGPointMake(NSMidX(self.frame), NSMidY(self.frame))
}
}