前段时间公司需要做一个身份识别的功能,而系统相机无法满足要求,so自己自定义了。

上代码:

.h文件

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController @property (nonatomic, strong) AVCaptureSession* session;
/**
* 输入设备
*/
@property (nonatomic, strong) AVCaptureDeviceInput* videoInput;
/**
* 照片输出流
*/
@property (nonatomic, strong) AVCaptureStillImageOutput* stillImageOutput;
/**
* 预览图层
*/
@property (nonatomic, strong) AVCaptureVideoPreviewLayer* previewLayer; /**
* 最后的缩放比例
*/
@property(nonatomic,assign)CGFloat effectiveScale;
@property (nonatomic, strong) UIView *backView;

.m文件

在这个文件你需要什么样的相机都可以在这里面设置,需要放大放小,闪光各种功能都在此处可以设置。

@interface ViewController ()

@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];

    if (self.session) {

        [self.session startRunning];
}
} - (void)viewDidDisappear:(BOOL)animated{ [super viewDidDisappear:YES]; if (self.session) { [self.session stopRunning];
}
} - (void)viewDidLoad {
self.view.backgroundColor = [UIColor blackColor]; self.backView = [[UIView alloc] initWithFrame:CGRectMake(, ,SelfWidth, SelfHeight - )];
[self.view addSubview:self.backView]; UIView *view = [[UIView alloc]initWithFrame:CGRectMake(SelfWidth/ - , SelfHeight - + , , )];
view.backgroundColor = [UIColor whiteColor];
view.layer.cornerRadius = ;
[view.layer masksToBounds];
[self.view addSubview:view]; //自己定义一个和原生的相机一样的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(SelfWidth/ - , SelfHeight - + , , );
button.backgroundColor = [UIColor whiteColor];
button.layer.cornerRadius = ;
button.layer.borderWidth = ;
button.layer.borderColor = [UIColor blackColor].CGColor;
[button.layer masksToBounds];
[button addTarget:self action:@selector(buttondown) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button]; //在相机中加个框
CALayer *Mylayer=[CALayer layer];
Mylayer.bounds=CGRectMake(, (SelfHeight - (SelfWidth - )/1.6)/, SelfWidth - , (SelfWidth - )/1.6);
Mylayer.position=CGPointMake(SelfWidth/, (SelfHeight - )/);
Mylayer.masksToBounds=YES;
Mylayer.borderWidth=;
Mylayer.borderColor=[UIColor whiteColor].CGColor;
[self.view.layer addSublayer:Mylayer]; UIButton *Lbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
Lbtn.frame = CGRectMake(, SelfHeight - , , );
[Lbtn setTitle:@"取消" forState:UIControlStateNormal];
Lbtn.titleLabel.font = [UIFont systemFontOfSize:];
[Lbtn setTintColor:[UIColor whiteColor]];
[Lbtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:Lbtn]; [self initAVCaptureSession]; //设置相机属性
self.effectiveScale = 1.0f;
} //设置相机属性
- (void)initAVCaptureSession{ self.session = [[AVCaptureSession alloc] init];
[self.session setSessionPreset:AVCaptureSessionPresetHigh]; NSError *error; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; //更改这个设置的时候必须先锁定设备,修改完后再解锁,否则崩溃
[device lockForConfiguration:nil];
//设置闪光灯为自动
[device setFlashMode:AVCaptureFlashModeAuto];
[device unlockForConfiguration]; self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
if (error) {
NSLog(@"%@",error);
}
self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
//输出设置。AVVideoCodecJPEG 输出jpeg格式图片
NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
[self.stillImageOutput setOutputSettings:outputSettings]; if ([self.session canAddInput:self.videoInput]) {
[self.session addInput:self.videoInput];
}
if ([self.session canAddOutput:captureOutput]) {
[self.session addOutput:captureOutput];
}
if ([self.session canAddOutput:self.stillImageOutput]) {
[self.session addOutput:self.stillImageOutput];
} //初始化预览图层
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
NSLog(@"%f",SelfWidth);
self.previewLayer.frame = CGRectMake(, ,SelfWidth, SelfHeight - );
self.backView.layer.masksToBounds = YES;
[self.backView.layer addSublayer:self.previewLayer];
}
- (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)deviceOrientation;
if ( deviceOrientation == UIDeviceOrientationLandscapeLeft )
result = AVCaptureVideoOrientationLandscapeRight;
else if ( deviceOrientation == UIDeviceOrientationLandscapeRight )
result = AVCaptureVideoOrientationLandscapeLeft;
return result;
} //照相按钮点击事件
-(void)buttondown{
NSLog(@"takephotoClick...");
AVCaptureConnection *stillImageConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation];
AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation:curDeviceOrientation];
[stillImageConnection setVideoOrientation:avcaptureOrientation];
[stillImageConnection setVideoScaleAndCropFactor:self.effectiveScale]; [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; [self makeImageView:jpegData];
NSLog(@"jpegDatajpegData == %ld",(unsigned long)[jpegData length]/); }];
} //拍照之后调到相片详情页面
-(void)makeImageView:(NSData*)data{ imageDetailViewController*imageView = [[imageDetailViewController alloc] init];
imageView.data = data; [self presentViewController:imageView animated:NO completion:nil]; }
//返回
-(void)back{ [self dismissViewControllerAnimated:YES completion:nil];
}

再进入详情页面进行照片的裁剪并显示

#import <UIKit/UIKit.h>

@interface imageDetailViewController : UIViewController

@property(nonatomic,strong)NSData *data;
@end
#import "imageDetailViewController.h"

@interface imageDetailViewController ()
{
UIImage *imageIm; }
@end @implementation imageDetailViewController - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(, -, SelfWidth, SelfHeight)];
imageView.image = [UIImage imageWithData:_data];
[self.view addSubview:imageView];
imageIm =[UIImage imageWithData:_data];
CGSize originalsize = [ imageView.image size]; NSLog(@"改变前图片的宽度为%f,图片的高度为%f",originalsize.width,originalsize.height);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(, SelfHeight - , , );
[button setTitle:@"重拍" forState:UIControlStateNormal];
[button setTintColor:[UIColor whiteColor]];
[button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button]; CALayer *Mylayer=[CALayer layer];
Mylayer.bounds=CGRectMake(, (SelfHeight - (SelfWidth - )/1.6)/, SelfWidth - , (SelfWidth - )/1.6);
Mylayer.position=CGPointMake(SelfWidth/, (SelfHeight - )/);
Mylayer.masksToBounds=YES;
Mylayer.borderWidth=;
Mylayer.borderColor=[UIColor whiteColor].CGColor;
[self.view.layer addSublayer:Mylayer]; UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
rightButton.frame = CGRectMake(SelfWidth - , SelfHeight - , , );
[rightButton setTitle:@"使用照片" forState:UIControlStateNormal];
[rightButton setTintColor:[UIColor whiteColor]];
[rightButton addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:rightButton]; // Do any additional setup after loading the view.
} -(void)rightButton{ //截取照片,截取到自定义框内的照片
imageIm = [self image:imageIm scaleToSize:CGSizeMake(SelfWidth, SelfHeight)];
//应为在展开相片时放大的两倍,截取时也要放大两倍
imageIm = [self imageFromImage:imageIm inRect:CGRectMake(*, (SelfHeight - (SelfWidth - ) /1.6)/*, (SelfWidth - )* , (SelfWidth - )/1.6*)]; //将图片存储到相册
UIImageWriteToSavedPhotosAlbum(imageIm, self, nil, nil); //截取之后将图片显示在照相时页面,和拍摄时的照片进行像素对比
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(, (SelfHeight - (SelfWidth - ) /1.6)/ + , SelfWidth - , (SelfWidth - )/1.6)];
imageView.image = imageIm;
[self.view addSubview:imageView]; } //截取图片
-(UIImage*)image:(UIImage *)imageI scaleToSize:(CGSize)size{
/*
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
CGSize size:指定将来创建出来的bitmap的大小
BOOL opaque:设置透明YES代表透明,NO代表不透明
CGFloat scale:代表缩放,0代表不缩放
创建出来的bitmap就对应一个UIImage对象
*/
UIGraphicsBeginImageContextWithOptions(size, NO, 2.0); //此处将画布放大两倍,这样在retina屏截取时不会影响像素 [imageI drawInRect:CGRectMake(, , size.width, size.height)]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage;
}
-(UIImage *)imageFromImage:(UIImage *)imageI inRect:(CGRect)rect{ CGImageRef sourceImageRef = [imageI CGImage]; CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; return newImage;
} -(void)back{
[self dismissViewControllerAnimated:NO completion:nil];
}

完整代码下载,GitHub:https://github.com/micaimanong/CameraDema

ios 相机 自定义 相片的截取的更多相关文章

  1. Android 实现 IOS相机滑动控件

     IOS相比于Android,动画效果是一方面优势,IOS相机切换时滑动的动画很不错,看着是有一个3D的效果,而且变化感觉很自然.Android也可以通过Graphics下面的Camera可以实现3D ...

  2. iOS 如何自定义UISearchBar 中textField的高度

    iOS 如何自定义UISearchBar 中textField的高度 只需设置下边的方法就可以 [_searchBar setSearchFieldBackgroundImage:[UIImage i ...

  3. iOS 隐藏自定义tabbar

    iOS  隐藏自定义tabbar -(void)viewWillAppear:(BOOL)animated { NSArray *array=self.tabBarController.view.su ...

  4. ios 实现自定义状态栏StatusBar 和 导航栏navigationBar 的状态和颜色

    很多app中可以看到不同与导航栏的状态栏的颜色,他妈的真绕嘴. 一.更改状态栏颜色 (StatusBar) 就是比如导航栏是红色的状态栏是绿色的. 要实现这样的效果其实很简单,就是添加一个背景view ...

  5. iOS中 自定义系统相机 作者:韩俊强

    需要框架: #import <AVFoundation/AVFoundation.h> #import <AssetsLibrary/AssetsLibrary.h> 布局如下 ...

  6. iOS 相机

    本章节主要为之前项目 JXHomepwner 添加照片功能(项目地址).具体任务就是显示一个 UIImagePickerController 对象,使用户能够为 JXItem 对象拍照并保存.拍摄的照 ...

  7. ios UIWebView自定义Alert风格的弹框

    之前开发过一个App,因为公司之前写好了网页版的内容和安卓版本的App,我进去后老板要求我ios直接用网页的内容,而不需要自己再搭建框架.我一听,偷笑了,这不就是一个UIWebView吗?简单! 但是 ...

  8. 【IOS】自定义可点击的多文本跑马灯YFRollingLabel

    需求 项目中需要用到跑马灯来仅展示一条消息,长度合适则不滚动,过长则循环滚动. 虽然不是我写的,但看了看代码,是在一个UIView里面放入两个UILabel, 在前一个快结束的时候,另一个显示.然而点 ...

  9. iOS - 使用自定义字体-苹方字体

    苹方提供了六个字重,font-family 定义如下:苹方-简 常规体font-family: PingFangSC-Regular, sans-serif;苹方-简 极细体font-family: ...

随机推荐

  1. __str__&__repr__

    [__str__&__repr__] object.__str__(self): Called by the str() built-in function and by the print  ...

  2. java基础之抽象类和接口的区别

    抽象类和接口的区别 A:成员区别 抽象类: 成员变量:可以是变量,也可以是常量 构造方法:有 成员方法:可以是抽象方法,也可以是非抽象方法 接口: 成员变量:只能是静态常量(不写修饰符,默认是 sta ...

  3. 接口自动化 Windows + HttpRunner 初探(一)

    运行环境 HttpRunner 是一个基于 Python 开发的测试框架,可以运行在 macOS.Linux.Windows 系统平台上. HttpRunner 的开发环境为 macOS + Pyth ...

  4. 监控服务器cpu、磁盘、模板以及自定义key

    一.检测主机存活 net.tcp.service.perf[tcp,,] Float型 返回0代表端口挂了 zabbix fping要开启sudo权限之类比较不方便 二.监控CPU负载 监控load ...

  5. fastdfs 清晰简介 有用

    是什么?         FastDFS是一个轻量级分布式文件系统. 能干嘛?         对文件进行管理,功能包括:文件存储.文件同步.文件访问(文件上传.文件下载)等. 在Linux上的安装连 ...

  6. 安装运行okvis odometry

    源码链接https://github.com/ethz-asl/okvis 1. 安装依赖项 sudo apt-get install cmake sudo apt-get install libgo ...

  7. Ubuntu命令行下安装、卸载、管理软件包的方法

    一.Ubuntu中软件安装方法 1.APT方式 (1)普通安装:apt-get install softname1 softname2 -; (2)修复安装:apt-get -f install so ...

  8. Anaconda 安装和配置

    Anaconda 安装和配置 1. Anaconda 安装 Anaconda说明及安装过程:Anaconda详细安装使用教程 2. Anaconda和Pip源修改 Anaconda源修改:打开Anac ...

  9. hibernate的hibernate.cfg.properties

    1.hibernate.cfg.properties  配置文件要放在工程目录src下,编译的时候会自动放在/bin目录下 ,所以Configuration configuration=new Con ...

  10. Word文档发布到CSDN博客

    目前大部分的博客作者在写博客这件事情上都会遇到以下3个痛点:1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.2.发布到博客或公众号平台 ...