1

アプリで 2 つの画像を回転させようとしています。そのうちの 1 つは北を指し、もう 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

1

新しいアニメーションを追加する前に、以前のアニメーションを削除してみてください。

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