我正在尝试在我的应用程序中旋转两个图像,其中一个指向北方,另一个指向指定坐标。
计算这些点之间方位角的代码viewDidLoad
是:
//start updating compass
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.headingFilter = 1;
locationManager.delegate=self;
[locationManager startUpdatingHeading];
//get coords of current location
CLLocation *location = [locationManager location];
CLLocationCoordinate2D fromLoc = [location coordinate];
//mecca:
CLLocationCoordinate2D toLoc = [location coordinate];
toLoc = CLLocationCoordinate2DMake(21.4167, 39.8167);
//calculate the bearing between current location and Mecca
float fLat = degreesToRadians(fromLoc.latitude);
float fLng = degreesToRadians(fromLoc.longitude);
float tLat = degreesToRadians(toLoc.latitude);
float tLng = degreesToRadians(toLoc.longitude);
float degree = radiandsToDegrees(atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng)));
if (degree >= 0) {
bearing = degree;
} else {
bearing = degree+360;
}
动画图像的代码是:
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
//compass
float oldRad = -manager.heading.trueHeading * M_PI / 180.0f;
float newRad = -newHeading.trueHeading * M_PI / 180.0f;
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
theAnimation.fromValue = [NSNumber numberWithFloat:oldRad];
theAnimation.toValue=[NSNumber numberWithFloat:newRad];
theAnimation.duration = 0.3f;
[compassImage.layer addAnimation:theAnimation forKey:@"animateMyRotation"];
compassImage.transform = CGAffineTransformMakeRotation(newRad);
NSLog(@"%f (%f) => %f (%f)", manager.heading.trueHeading, oldRad, newHeading.trueHeading, newRad);
//needle
//float MoldRad = (-manager.heading.trueHeading - bearing) * M_PI / 180.0f; //tried this, but it causes needle to spin a lot
float MnewRad = (180 + bearing) * M_PI / 180.0f;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
theAnimation.fromValue = [NSNumber numberWithFloat:MoldRad];
theAnimation.toValue=[NSNumber numberWithFloat:MnewRad];
theAnimation.duration = 0.6f;
[needleImage.layer addAnimation:theAnimation forKey:@"animateMyRotation"];
needleImage.transform = CGAffineTransformMakeRotation(MnewRad);
MoldRad = MnewRad;
NSLog(@"%f (%f) => %f (%f)", manager.heading.trueHeading, MoldRad, newHeading.trueHeading, MnewRad);
}
指南针旋转完美,但指针并不总是如此。它首先正确加载,但不会像应用程序那样转动。我认为这与它没有被重新计算有关,但无法弄清楚如何记住它的“旧”位置,以便它可以正确设置动画。
任何想法为什么它不起作用?
非常感谢!