iOS 自定义照相机

声明

import

import

import “DZC_TakePhoto.h”

@interface DZC_TakePhoto ()

@end

@implementation DZC_TakePhoto
-(instancetype)init
{
self=[super init];
if (self)
{
[self initialSession];
return self;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *carmerBtn=[[UIButton alloc]initWithFrame:CGRectMake(SCREENWIDTH/2-50, SCREENHEIGHT-100, 100, 50)];
// //[carmerBtn setTransform:CGAffineTransformMakeRotation(M_PI/2)];
[carmerBtn setTitle:@”拍照” forState:UIControlStateNormal];
carmerBtn.backgroundColor=[UIColor orangeColor];
[carmerBtn addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside];
self.shutterButton=carmerBtn;
[self.view addSubview:carmerBtn];
[self.view bringSubviewToFront:carmerBtn];
UIButton *returnBtn=[[UIButton alloc]initWithFrame:CGRectMake(10, SCREENHEIGHT-100, 100, 50)];
//[returnBtn setTransform:CGAffineTransformMakeRotation(M_PI/2)];
[returnBtn setTitle:@”撤销” forState:UIControlStateNormal];
returnBtn.backgroundColor=[UIColor orangeColor];
[returnBtn addTarget:self action:@selector(CloseBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:returnBtn];
[self.view bringSubviewToFront:returnBtn];
// Do any additional setup after loading the view.
}
-(void)CloseBtn
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) initialSession
{
//这个方法的执行我放在init方法里了
self.session = [[AVCaptureSession alloc] init];
[self.session setSessionPreset:AVCaptureSessionPresetMedium];
self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:nil];
//[self fronCamera]方法会返回一个AVCaptureDevice对象,因为我初始化时是采用前摄像头,所以这么写,具体的实现方法后面会介绍
self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
//这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片
[self.stillImageOutput setOutputSettings:outputSettings];

if ([self.session canAddInput:self.videoInput]) {
    [self.session addInput:self.videoInput];
}
if ([self.session canAddOutput:self.stillImageOutput]) {
    [self.session addOutput:self.stillImageOutput];
}

}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == position) {
_cameraAvaible=YES;
return device;
}
}
_cameraAvaible=NO;
return nil;
}

  • (AVCaptureDevice *)frontCamera {
    return [self cameraWithPosition:AVCaptureDevicePositionFront];
    }

  • (AVCaptureDevice *)backCamera {
    return [self cameraWithPosition:AVCaptureDevicePositionBack];
    }
    //接下来在viewWillAppear方法里执行加载预览图层的方法

  • (void) setUpCameraLayer
    {
    if (_cameraAvaible == NO) return;

    if (self.previewLayer == nil) {
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.videoGravity=AVLayerVideoGravityResizeAspect;
    self.previewLayer.frame=CGRectMake(0,0, SCREENWIDTH, SCREENHEIGHT);
    self.previewLayer.position=CGPointMake(SCREENWIDTH/2, SCREENHEIGHT/2);
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];

    }
    }
    -(void)viewWillAppear:(BOOL)animated
    {
    [super viewWillAppear:animated];
    [self setUpCameraLayer];
    }
    //在viewDidAppear和viewDidDisappear方法中启动和关闭session

  • (void) viewDidAppear:(BOOL)animated
    {
    [super viewDidAppear:animated];
    if (self.session) {
    [self.session startRunning];
    }
    }

  • (void) viewDidDisappear:(BOOL)animated
    {
    [super viewDidDisappear: animated];
    if (self.session) {
    [self.session stopRunning];
    }
    }
    //这是切换镜头的按钮方法

  • (void)toggleCamera {
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
    NSError *error;
    AVCaptureDeviceInput *newVideoInput;
    AVCaptureDevicePosition position = [[_videoInput device] position];

    if (position == AVCaptureDevicePositionBack)
        newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];
    else if (position == AVCaptureDevicePositionFront)
        newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];
    else
        return;
    
    if (newVideoInput != nil) {
        [self.session beginConfiguration];
        [self.session removeInput:self.videoInput];
        if ([self.session canAddInput:newVideoInput]) {
            [self.session addInput:newVideoInput];
            [self setVideoInput:newVideoInput];
        } else {
            [self.session addInput:self.videoInput];
        }
        [self.session commitConfiguration];
    } else if (error) {
        NSLog(@"toggle carema failed, error = %@", error);
    }
    

    }
    }
    // 这是拍照按钮的方法

  • (void) shutterCamera
    {
    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
    NSLog(@”take photo failed!”);
    return;
    }

    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
    if (imageDataSampleBuffer == NULL) {
    return;
    }
    NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
    UIImage * image = [UIImage imageWithData:imageData];
    DLog(@”image size = %@”,NSStringFromCGSize(image.size));
    [self.delegate PassImagedata:image];
    [self dismissViewControllerAnimated:YES completion: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yijianliuxiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值