1

我正在尝试在我的应用程序中旋转两个图像,其中一个指向北方,另一个指向指定坐标。

计算这些点之间方位角的代码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);

}

指南针旋转完美,但指针并不总是如此。它首先正确加载,但不会像应用程序那样转动。我认为这与它没有被重新计算有关,但无法弄清楚如何记住它的“旧”位置,以便它可以正确设置动画。

任何想法为什么它不起作用?

非常感谢!

4

2 回答 2

2

不要为旋转设置动画。

当您从 CoreMotion 收到方向已更改的通知时,只需更改旋转即可。

这种情况经常发生,以至于更改非常小,因此根本不使用动画就看起来像史密斯。

于 2013-07-02T09:57:13.387 回答
1

也许您可以尝试在添加新动画之前删除以前的动画。

[view.layer removeAllAnimations]
于 2013-07-02T09:51:50.063 回答