iOS 指南针的制作 附带源码

iOS  指南针的制作  附带源码




代码下载地址:





指南针的制作非常简单。
直接看代码吧!
ViewController.h代码如下:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<CLLocationManagerDelegate>

@property (retain, nonatomic) UIImageView *compassImageView;
@property (retain, nonatomic) CLLocationManager *locationManager;
@end

ViewController.m代码如下:
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView* backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BackGroundPad.png"]];
    [self.view addSubview:backgroundImage];
    //创建指南针图片
    self.compassImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Compass_HD.png"]];
    
    self.compassImageView.center = CGPointMake(370, 500);
    [self.view addSubview:self.compassImageView];
    //初始化locationManager并设置代理类
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
	if ([CLLocationManager headingAvailable]) {
        //设置精度
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置滤波器不工作
        self.locationManager.headingFilter = kCLHeadingFilterNone;
        //开始更新
        [self.locationManager startUpdatingHeading];
    }
    else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"atention" message:@"compass not Available" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    }
}

//调用locationManager成员方法
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading

{
    //重置view的位置
    self.compassImageView.transform = CGAffineTransformIdentity;      
    CGAffineTransform transform = CGAffineTransformMakeRotation(-1 * M_PI*newHeading.magneticHeading/180.0);
    self.compassImageView.transform = transform;
}

这样就OK啦 ! 要在真机上测试哦!!!


原文地址:https://www.cnblogs.com/jiangu66/p/3162859.html