我想在我的应用程序中包含一个指南针和标签,重力旋转并保持其作为iOS应用程序指南针的位置。
我已经完成了一些代码并单独运行,但是当它们一起工作时会变得疯狂。
这是我使用的代码的一部分:
UIImageView * imgCompass; UIImageView * north;
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.headingFilter = 1;
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];
motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = 0.01;
motionManager.gyroUpdateInterval = 0.01;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
if (!error) {
[self outputAccelertionData:accelerometerData.acceleration];
}
else{
NSLog(@"%@", error);
}
}];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
// Convert Degree to Radian and move the needle
newRad = -newHeading.trueHeading * M_PI / 180.0f;
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.viewCompass.transform = CGAffineTransformMakeRotation(newRad);
} completion:nil];
}
- (void)outputAccelertionData:(CMAcceleration)acceleration{
//UIInterfaceOrientation orientationNew;
// Get the current device angle
float xx = -acceleration.x;
float yy = acceleration.y;
float angle = atan2(yy, xx);
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
// Add 1.5 to the angle to keep the image constantly horizontal to the viewer.
[self.north setTransform:CGAffineTransformMakeRotation(angle - 1.5)];
} completion:nil];
}
有什么想法吗?谢谢。我很绝望......
答案 0 :(得分:0)
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
self.lblGrados.text = [NSString stringWithFormat:@"%.0f°", newHeading.magneticHeading];
// Convert Degree to Radian and move the needle
newRad = -newHeading.trueHeading * M_PI / 180.0f;
[UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
compassView.transform = CGAffineTransformMakeRotation(newRad);
} completion:nil];
[UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.north setTransform:CGAffineTransformMakeRotation(-newRad)];
[self.south setTransform:CGAffineTransformMakeRotation(-newRad)];
[self.east setTransform:CGAffineTransformMakeRotation(-newRad)];
[self.west setTransform:CGAffineTransformMakeRotation(-newRad)];
} completion:nil];
}