iOS 指南针

  • 需求:
    • 让指南针图片不断指向磁北方向
指南针图片.png

一、实现思路:

  • 1.获取手机设备朝向(距离磁北方向的角度)
  • 2.让指南针图片反向旋转对应角度,这样就可以不断指向磁北
    • 获取手机朝向: [locationM startUpdatingHeading];
    • magneticHeading(磁北方向和真北方向,取值范围:0-359.9;顺时针为正)

二、实现步骤:

  • 1.导入CoreLocation框架和对应的主头文件

import <CoreLocation/CoreLocation.h>

``` 

+2.创建CLLcationManager对象,并设置代理
objc _locationM = [[CLLocationManager alloc] init]; _locationM.delegate = self;

  • 3.调用CLLcationManager对象的startUpdatingHeading方法进行更新设备朝向

[_locationM startUpdatingHeading];
```

  • 4.实现代理方法,获取方向参数,根据方向参数旋转图片

-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateHeading:(nonnull CLHeading *)newHeading
{
// 获取当前设备朝向(磁北方向)
CGFloat angle = newHeading.magneticHeading;

    // 转换成为弧度
     CGFloat radian = angle / 180.0 * M_PI;

   // 反向旋转指南针
     [UIView animateWithDuration:0.5 animations:^{
         self.compassView.transform = CGAffineTransformMakeRotation(-radian);
    }];
 }

### 注意
+ 注意: 获取用户的设备朝向,不需要用户进行定位授权 
+ 0.使用之前先判断方向服务是否可用
+ 1.获取手机设备朝向(使用的是”磁力计”传感器)不需要用户定位授权
+ 2.设备朝向(使用的是”磁力计”传感器)和航向course的区别(gps定位确定)

### 应用场景
- 1.指南针
- 2.一些比较有创意的app(“随便走”,是我见过把传感器利用的最有创意的一个app)


## 三、代码实现

```objc
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *compassView;

/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager *locationM;


@end

@implementation ViewController


#pragma mark -懒加载
-(CLLocationManager *)locationM
{
  if (!_locationM) {
      _locationM = [[CLLocationManager alloc] init];
      _locationM.delegate = self;
  }
  return _locationM;
}

- (void)viewDidLoad {

  // 获取当前设备朝向
  [self.locationM startUpdatingHeading];
}


#pragma mark -CLLocationManagerDelegate

// 已经更新到用户设备朝向时调用
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{

  // magneticHeading : 距离磁北方向的角度
  // trueHeading : 真北
  // headingAccuracy : 如果是负数,代表当前设备朝向不可用
  if (newHeading.headingAccuracy < 0) {
      return;
  }
  
  // 角度
  CLLocationDirection angle = newHeading.magneticHeading;
  
  // 角度-> 弧度
  double radius = angle / 180.0 * M_PI;
  
  // 反向旋转图片(弧度)
  [UIView animateWithDuration:0.5 animations:^{
          self.compassView.transform = CGAffineTransformMakeRotation(-radius);
  }];
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言: 这个小项目使用到了CoreLocation框架里面的设备朝向功能,对CoreLocation感兴趣的可以翻...
    珍此良辰阅读 2,245评论 0 3
  • 简介 在移动互联网时代,移动app能解决用户的很多生活琐事,比如 周边:找餐馆、找KTV、找电影院等等 导航:根据...
    JonesCxy阅读 1,238评论 1 1
  • CoreLocation框架 一. iOS8.0之前的定位(✨✨✨✨✨) 前台定位导入CoreLocation框架...
    尼古拉斯赵四爷阅读 996评论 0 2
  • 一. iOS8.0之前的定位(✨✨✨✨✨) 1. 前台定位 导入CoreLocation框架以及对应的主头文件 #...
    走道牙的人阅读 238评论 0 0
  • CoreLocation框架 一. iOS8.0之前的定位 1. 前台定位 导入CoreLocation框架以及对...
    iOS_Cqlee阅读 1,384评论 1 2