#import "AppDelegate.h"
#import "GDViewController.h"
#import
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
[AMapServices sharedServices].apiKey = @"Your Key";
// Override point for customization after application launch.
return YES;
}
ViewController.m
#import "ViewController.h"
#import "oneViewController.h"
#import "twoViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
oneViewController *one = [oneViewController new];
UINavigationController *oneNav = [[UINavigationController alloc]initWithRootViewController:one];
oneNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"哈哈" image:[UIImage imageNamed:@"1.png"] selectedImage:[UIImage imageNamed:@"2.png"]];
twoViewController *two = [twoViewController new];
UINavigationController *twoNav = [[UINavigationController alloc]initWithRootViewController:two];
two.tabBarItem =[[UITabBarItem alloc]initWithTitle:@"呵呵" image:[UIImage imageNamed:@"2.png"] selectedImage:[UIImage imageNamed:@"1.png"]];
self.viewControllers=@[oneNav,twoNav];
}
@end
oneViewController.h
#import "oneViewController.h"
#import "twoViewController.h"
#import "threeViewController.h"
#import "fourViewController.h"
#import "GDViewController.h"
@interface oneViewController ()
@end
@implementationoneViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"哈哈" style:UIBarButtonItemStylePlain target:self action:@selector(right)];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"登陆" style:UIBarButtonItemStylePlain target:self action:@selector(left)];
self.view.backgroundColor = [UIColor redColor];
UISearchBar *sea = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
sea.placeholder = @"请输入你想要的商品";
self.navigationItem.titleView = sea;
sea.backgroundColor = [UIColor whiteColor];
}
-(void)left{
fourViewController *four = [fourViewController new];
[self presentViewController:four animated:YES completion:nil];
}
-(void)right{
threeViewController *three = [threeViewController new];
[self.navigationController pushViewController:three animated:YES];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
threeViewController
#import "threeViewController.h"
#import "GDViewController.h"
@interface threeViewController ()
@end
@implementationthreeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"地图" style:UIBarButtonItemStylePlain target:self action:@selector(MapView:)];
}
-(void)MapView:(id)send{
GDViewController *gd = [GDViewController new];
[self presentViewController:gd animated:YES completion:nil];
}
fourViewController
#import "fourViewController.h"
#import "smewmViewController.h"
#import "scewmViewController.h"
@interface fourViewController ()
- (IBAction)SMEWM:(id)sender;
- (IBAction)BackPress:(id)sender;
- (IBAction)LoginPress:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *TextFile;
@property (weak, nonatomic) IBOutlet UITextField *TextFile1;
- (IBAction)SCEWM:(id)sender;
@end
@implementationfourViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)SMEWM:(id)sender {
smewmViewController *sm = [smewmViewController new];
[self presentViewController:sm animated:YES completion:nil];
}
- (IBAction)BackPress:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)LoginPress:(id)sender {
}
- (IBAction)SCEWM:(id)sender {
scewmViewController *sc = [scewmViewController new];
[self presentViewController:sc animated:YES completion:nil];
}
@end
scewmViewController
#import "scewmViewController.h"
#import "QRCodeGenerator.h"
@interface scewmViewController ()
{
UITextField*field;
UIButton*btn;
UIImageView*imgVV;
}
- (IBAction)Back:(id)sender;
@end
@implementationscewmViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//文本框的位置
field = [[UITextField alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2, 100, 200, 44)];
//提示文字
field.placeholder = @"请输入内容";
field.borderStyle = UITextBorderStyleRoundedRect;
//添加到视图
[self.view addSubview:field];
//按钮的位置
btn = [[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2, 180, 200, 44)];
//为按钮设置文字
[btn setTitle:@"点击生成二维码" forState:UIControlStateNormal];
//为按钮设置背景颜色
btn.backgroundColor = [UIColor lightGrayColor];
//给按钮添加一个点击方法
[btn addTarget:self action:@selector(abc) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)abc{
// 设置UIImageView的位置
imgVV = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2, 300, 200, 200)];
//为UIImageView设置二维码图片
imgVV.image = [QRCodeGenerator qrImageForString:field.text imageSize:imgVV.bounds.size.width];
//把图片添加到视图
[self.view addSubview:imgVV];
// Do any additional setup after loading the view.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)Back:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
smewmViewController
#import "smewmViewController.h"
#import
#define KMainW [UIScreen mainScreen].bounds.size.width
#define KMainH [UIScreen mainScreen].bounds.size.height
@interface smewmViewController ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;
@property (nonatomic, weak) UIImageView *line;
@property (nonatomic, assign) NSInteger distance;
@end
@implementationsmewmViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initInfo];
//创建控件
[self creatControl];
//设置参数
[self setupCamera];
//添加定时器
[self addTimer];
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self stopScanning];
}
-(void)initInfo
{
//背景色
self.view.backgroundColor = [UIColor blackColor];
//导航标题
self.navigationItem.title = @"二维码/条形码";
//导航右侧相册按钮
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(photoBtnOnClick)];
}
-(void)creatControl
{
CGFloatscanW =KMainW*0.65;
CGFloatpadding =10.0f;
CGFloatlabelH =20.0f;
CGFloattabBarH =64.0f;
CGFloatcornerW =26.0f;
CGFloatmarginX = (KMainW- scanW) *0.5;
CGFloatmarginY = (KMainH- scanW - padding - labelH) *0.5;
//遮盖视图
for(inti =0; i <4; i++) {
UIView*cover = [[UIViewalloc]initWithFrame:CGRectMake(0, (marginY + scanW) * i,KMainW, marginY + (padding + labelH) * i)];
if(i ==2|| i ==3) {
cover.frame=CGRectMake((marginX + scanW) * (i -2), marginY, marginX, scanW);
}
cover.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
[self.viewaddSubview:cover];
}
//扫描视图
UIView*scanView = [[UIViewalloc]initWithFrame:CGRectMake(marginX, marginY, scanW, scanW)];
[self.viewaddSubview:scanView];
//扫描线
UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, scanW, 2)];
[self drawLineForImageView:line];
[scanViewaddSubview:line];
self.line= line;
//边框
UIView*borderView = [[UIViewalloc]initWithFrame:CGRectMake(0,0, scanW, scanW)];
borderView.layer.borderColor = [[UIColor whiteColor] CGColor];
borderView.layer.borderWidth=1.0f;
[scanViewaddSubview:borderView];
//扫描视图四个角
for(inti =0; i <4; i++) {
CGFloatimgViewX = (scanW - cornerW) * (i %2);
CGFloatimgViewY = (scanW - cornerW) * (i /2);
UIImageView*imgView = [[UIImageViewalloc]initWithFrame:CGRectMake(imgViewX, imgViewY, cornerW, cornerW)];
if(i ==0|| i ==1) {
imgView.transform = CGAffineTransformRotate(imgView.transform, M_PI_2 * i);
}else{
imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI_2* (i -1));
}
[self drawImageForImageView:imgView];
[scanViewaddSubview:imgView];
}
//提示标签
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(scanView.frame) + padding, KMainW, labelH)];
label.text = @"将二维码/条形码放入框内,即可自动扫描";
label.font = [UIFont systemFontOfSize:16.0f];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
[self.viewaddSubview:label];
//选项栏
UIView*tabBarView = [[UIViewalloc]initWithFrame:CGRectMake(0,KMainH- tabBarH,KMainW, tabBarH)];
tabBarView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8f];
[self.viewaddSubview:tabBarView];
//开启照明按钮
UIButton *lightBtn = [[UIButton alloc] initWithFrame:CGRectMake(KMainW - 100, 0, 100, tabBarH)];
lightBtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
[lightBtnsetTitle:@"开启照明" forState:UIControlStateNormal];
[lightBtnsetTitle:@"关闭照明" forState:UIControlStateSelected];
[lightBtnaddTarget:self action:@selector(lightBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
[tabBarViewaddSubview:lightBtn];
}
-(void)setupCamera
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//初始化相机设备
self->_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//初始化输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self->_device error:nil];
//初始化输出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
//设置代理,主线程刷新
[outputsetMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化链接对象
self->_session = [[AVCaptureSession alloc] init];
//高质量采集率
[self->_session setSessionPreset:AVCaptureSessionPresetHigh];
if([self->_sessioncanAddInput:input]) [self->_sessionaddInput:input];
if([self->_sessioncanAddOutput:output]) [self->_sessionaddOutput:output];
//条码类型(二维码/条形码)
// output.metadataObjectTypes = [NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil];
//更新界面
dispatch_async(dispatch_get_main_queue(), ^{
self->_preview = [AVCaptureVideoPreviewLayer layerWithSession:self->_session];
self->_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
self->_preview.frame=CGRectMake(0,0,KMainW,KMainH);
[self.view.layer insertSublayer:self->_preview atIndex:0];
[self->_sessionstartRunning];
});
});
}
-(void)addTimer
{
_distance = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)timerAction
{
if(_distance++ >KMainW*0.65)_distance=0;
_line.frame=CGRectMake(0,_distance,KMainW*0.65,2);
}
-(void)removeTimer
{
[_timer invalidate];
_timer=nil;
}
-(void)lightBtnOnClick:(UIButton*)btn
{
//判断是否有闪光灯
if(![_devicehasTorch]) {
[selfshowAlertWithTitle:@"当前设备没有闪光灯,无法开启照明功能"message:nilsureHandler:nilcancelHandler:nil];
return;
}
btn.selected= !btn.selected;
[_device lockForConfiguration:nil];
if(btn.selected) {
[_device setTorchMode:AVCaptureTorchModeOn];
}else{
[_device setTorchMode:AVCaptureTorchModeOff];
}
[_device unlockForConfiguration];
}
-(void)photoBtnOnClick
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
controller.delegate=self;
[self presentViewController:controller animated:YES completion:nil];
}else{
[self showAlertWithTitle:@"当前设备不支持访问相册" message:nil sureHandler:nil cancelHandler:nil];
}
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection
{
//扫描完成
if([metadataObjectscount] >0) {
//停止扫描
[self stopScanning];
//显示结果
[selfshowAlertWithTitle:@"扫描结果"message:[[metadataObjectsfirstObject]stringValue]sureHandler:nilcancelHandler:nil];
}
}
-(void)stopScanning
{
[_session stopRunning];
_session = nil;
[_preview removeFromSuperlayer];
[self removeTimer];
}
#pragma mark - UIImagePickerControllrDelegate
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionaryid> *)info
{
[pickerdismissViewControllerAnimated:YES completion:^{
//获取相册图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
//识别图片
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
//识别结果
if(features.count>0) {
[selfshowAlertWithTitle:@"扫描结果"message:[[featuresfirstObject]messageString]sureHandler:nilcancelHandler:nil];
}else{
[selfshowAlertWithTitle:@"没有识别到二维码或条形码"message:nilsureHandler:nilcancelHandler:nil];
}
}];
}
//提示弹窗
-(void)showAlertWithTitle:(NSString*)title message:(NSString*)message sureHandler:(void(^)())sureHandler cancelHandler:(void(^)())cancelHandler
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:sureHandler];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:cancelHandler];
[alertControlleraddAction:sureAction];
[alertControlleraddAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)drawImageForImageView:(UIImageView*)imageView
{
UIGraphicsBeginImageContext(imageView.bounds.size);
//获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//设置线条宽度
CGContextSetLineWidth(context, 6.0f);
//设置颜色
CGContextSetStrokeColorWithColor(context, [[UIColor greenColor] CGColor]);
//路径
CGContextBeginPath(context);
//设置起点坐标
CGContextMoveToPoint(context, 0, imageView.bounds.size.height);
//设置下一个点坐标
CGContextAddLineToPoint(context, 0, 0);
CGContextAddLineToPoint(context, imageView.bounds.size.width, 0);
//渲染,连接起点和下一个坐标点
CGContextStrokePath(context);
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
//绘制线图片
-(void)drawLineForImageView:(UIImageView*)imageView
{
CGSizesize = imageView.bounds.size;
UIGraphicsBeginImageContext(size);
//获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//创建一个颜色空间
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//设置开始颜色
const CGFloat *startColorComponents = CGColorGetComponents([[UIColor greenColor] CGColor]);
//设置结束颜色
const CGFloat *endColorComponents = CGColorGetComponents([[UIColor whiteColor] CGColor]);
//颜色分量的强度值数组
CGFloatcomponents[8] = {startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]
};
//渐变系数数组
CGFloatlocations[] = {0.0,1.0};
//创建渐变对象
CGGradientRefgradient =CGGradientCreateWithColorComponents(colorSpace, components, locations,2);
//绘制渐变
CGContextDrawRadialGradient(context, gradient, CGPointMake(size.width * 0.5, size.height * 0.5), size.width * 0.25, CGPointMake(size.width * 0.5, size.height * 0.5), size.width * 0.5, kCGGradientDrawsBeforeStartLocation);
//释放
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
@end
GDViewController
#import "GDViewController.h"
#import
#import
@interface GDViewController ()
@property(nonatomic , strong)CLLocationManager *manager;
@property(nonatomic , strong)MAMapView *mapView;
@end
@implementationGDViewController
-(MAMapView*)mapView{
if(!_mapView) {
_mapView = [[MAMapView alloc]initWithFrame:self.view.frame];
//普通地图
_mapView.mapType = MAMapTypeStandard;
_mapView.showsUserLocation = YES;
//代理
_mapView.delegate = self;
}
return _mapView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.manager = [[CLLocationManager alloc]init];
self.manager.delegate=self;
[self.manager requestWhenInUseAuthorization];
//指南针
self.navigationController.navigationBar.translucent = NO;
[self.view addSubview:self.mapView];
}
-(IBAction)getCyrrentLocation:(id)sender{
NSLog(@"获取当前位置");
//更新位置信息
[self.manager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray *)locations{
//获取当前位置
CLLocation*cuLocation = [locationslastObject];
//经纬度
CLLocationCoordinate2D curCoor =cuLocation.coordinate;
NSLog(@"-----------");
dispatch_async(dispatch_get_main_queue(), ^{
//地图显示区域
MACoordinateRegion showRegin = MACoordinateRegionMakeWithDistance(curCoor, 800, 800);
//实例化一个大头针
MAPointAnnotation *point = [[MAPointAnnotation alloc]init];
point.coordinate= curCoor;
point.title=@"当前位置";
//地理解析
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoderreverseGeocodeLocation:cuLocationcompletionHandler:^(NSArray *_Nullableplacemarks,NSError*_Nullableerror) {
CLPlacemark*place = [placemarkslastObject];
point.subtitle= place.name;
//回到UI主线程,给地图添加注释视图
dispatch_async(dispatch_get_main_queue(), ^{
// [self.mapView = nil];
});
}];
});
}
-(MAMapView*)mapView:(MAMapView*)mapView viewForAnnotation:(id)annotation{
if([annotationisKindOfClass:[MAPointAnnotationclass]]) {
staticNSString*pointReuseIndentifier =@"pointReuseIndentifier";
MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapViewdequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
if(annotationView ==nil) {
annotationView = [[MAPinAnnotationViewalloc]initWithAnnotation:annotationreuseIdentifier:pointReuseIndentifier];
}
annotationView.canShowCallout=YES;
annotationView.animatesDrop=YES;
annotationView.draggable=YES;
annotationView.pinColor = MAPinAnnotationColorPurple;
returnannotationView;
}
return nil;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end