Raptor
Raptor

Reputation: 54212

Rotate UIView according to iDevice Magnetometer reading

I have a UIView containing some points within, and I make it rotate according to the readings from magnetometer via CLLocationManager, as follow:

@interface PresentationVC () {
    float initialBearing;
}
@end

@implementation PresentationVC
- (void)viewDidLoad {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingHeading];
    [self.locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    if(initialBearing == 0) {
        initialBearing = newHeading.magneticHeading;
    }
    NSLog(@"Magnetic Heading: %f", newHeading.magneticHeading);
    viewMap.transform = CGAffineTransformMakeRotation(degreesToRadians(initialBearing - newHeading.magneticHeading));
}

@end

where viewMap is the UIView.

The above code works, but I want the transform of UIView set to 0 degree / radian, which is CGAffineTransformMakeRotation(0). Currently it sets to current bearing initially, which is, for example, 157 degree.

I try to use initialBearing in the above code to calculate the offset angle, but it still rotates to an angle initially. What did I miss?

Also, I can't rotate a full 360 degree; the CGAffineTransformMakeRotation() bounces back the rotation when I turn almost 180 degree instead. How can I rotate a full 360 degree rotation without bouncing? (I guess it's about radian degree issue)

Upvotes: 0

Views: 148

Answers (1)

Raptor
Raptor

Reputation: 54212

End up I found that the degreeToRadians() is malfunctioning, making the radian calculation incorrect.

// this is malfunctioned
#define degreesToRadians(degrees) (M_PI * degrees / 180.0)

// this is working, thanks @TonyMkenu
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)

Upvotes: 1

Related Questions