Objective C UIImageView旋转动画效果不佳

时间:2011-11-30 18:52:45

标签: objective-c animation uiimageview rotatetransform

我在表格单元格中创建指南针,因此我对图像视图的旋转有问题,它从资源中的图像位置重新开始。

这是我的代码的一部分:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDelegate:self];

if(cellValue.direction == 0){
   cell.compass.transform = CGAffineTransformRotate(cell.compass.transform,DegreesToRadians([cellValue.fixedDirection floatValue]));
} else {
   cell.compass.transform = CGAffineTransformRotate(cell.compass.transform,DegreesToRadians([cellValue.direction floatValue]));   
}
[UIView commitAnimations];

cell.compass是UIimageView,我的图像是箭头垂直的。如果方向是0那么它应该达到那个程度,在它从罗盘获得角度之后它会进入else子句。因此,图像会从垂直位置旋转,而不是从最后一个旋转位置旋转。

如何获得最后一个旋转位置并从那里继续

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用removedOnCompletion = NO旋转视图的图层,而不是旋转UIView

CALayer *layer = [cell.compass layer];
NSNumber *initRotation = [layer valueForKeyPath:@"transform.rotation"];
//CATransform3D rotationTransform = CATransform3DRotate(layer.transform, angle, 0.0, 0.0, 1.0);
//layer.transform = rotationTransform;

CABasicAnimation *animation =[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
animation.duration = 0.5;
animation.fromValue = initRotation ;
animation.toValue = [NSNumber numberWithFloat:([initRotation floatValue] + angle)];
animation.removedOnCompletion = NO;
[layer addAnimation:animation forKey:@"transform.rotation"];

答案 1 :(得分:0)

我找到了解决这个问题的方法:

NSLog(@"old dir %d: new dir: %d", [cellValue.oldDirection intValue], [cellValue.direction intValue]);
CABasicAnimation *animation =[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
animation.duration = 0.5;

int oldDir = [cellValue.oldDirection intValue];
int newDir = [cellValue.direction intValue];


/// in didUpdateHeading
/// int result = 0;

/// result = fixedDir - orientation; 

/// place.oldDirection = place.direction;
/// place.direction = [NSNumber numberWithInt:result];

固定目录是从北到该地方的度数方向! and orientation是指南针或trueHeading

的当前方向
if (oldDir*newDir < 0 && abs(abs(oldDir) - abs(newDir)) < 180) {
    oldDir = (360 + oldDir) % 360;
    newDir = (360 + newDir) % 360;
}

animation.fromValue = [NSNumber numberWithFloat:DegreesToRadians(oldDir)];
animation.toValue = [NSNumber numberWithFloat:DegreesToRadians(newDir)];


animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[cell.compass.layer addAnimation:animation forKey:@"transform.rotation"];
float differenceAngle = [animation.toValue floatValue] - [animation.fromValue floatValue];
CATransform3D rotationTransform = CATransform3DMakeAffineTransform(CGAffineTransformRotate(cell.compass.transform,differenceAngle));

cell.compass.layer.transform = rotationTransform;

我希望我帮助过。)