欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS开发中对于摄像头的一些基本使用方法分享

程序员文章站 2022-04-30 21:38:07
在一些应用中,我们需要用到ios设备的摄像头进行拍照,视频。并且从相册中选取我们需要的图片或者视频。 关于ios摄像头和相册的应用,可以使用uiimagepickerco...

在一些应用中,我们需要用到ios设备的摄像头进行拍照,视频。并且从相册中选取我们需要的图片或者视频。
关于ios摄像头和相册的应用,可以使用uiimagepickercontroller类来完成控制。

uiimagepickercontroller 这个类可以为大家提供照相的功能,以及图片,视频浏览的功能。


检查硬件是否安装有摄像头或者允许操作相册

复制代码 代码如下:

#pragma mark - 摄像头和相册相关的公共类


// 判断设备是否有摄像头
- (bool) iscameraavailable{
return [uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypecamera];
}


// 前面的摄像头是否可用
- (bool) isfrontcameraavailable{
return [uiimagepickercontrolleriscameradeviceavailable:uiimagepickercontrollercameradevicefront];
}


// 后面的摄像头是否可用
- (bool) isrearcameraavailable{
return [uiimagepickercontrolleriscameradeviceavailable:uiimagepickercontrollercameradevicerear];
}

调用摄像头

复制代码 代码如下:
- (bool) hasmultiplecameras {
nsarray *devices = [avcapturedevice deviceswithmediatype:avmediatypevideo];
if (devices != nil && [devices count] > 1) return yes;
return no;
}

- (avcapturedevice *)camerawithposition : (avcapturedeviceposition) position
{
nsarray *devices = [avcapturedevice deviceswithmediatype:avmediatypevideo];
for (avcapturedevice *device in devices )
if ( device.position == position )
return device;

return nil ;
}

- (void) swapfrontandbackcameras {
//check for available cameras!
if (![self hasmultiplecameras]) return;

//assumes session is running
nsarray *inputs = self.capturesession.inputs; //should only be one value!
for ( avcapturedeviceinput *capturedeviceinput in inputs ) {
avcapturedevice *device = capturedeviceinput.device ;
if ( [device hasmediatype:avmediatypevideo ] ) {
avcapturedeviceposition position = device.position ;
avcapturedevice *newcamera = nil ;
avcapturedeviceinput *newinput = nil ;

if (position == avcapturedevicepositionfront)
newcamera = [self camerawithposition:avcapturedevicepositionback];
else
newcamera = [self camerawithposition:avcapturedevicepositionfront];

[self initializecapturedevice:newcamera];
newinput = [avcapturedeviceinput deviceinputwithdevice:newcamera error:nil];

// beginconfiguration ensures that pending changes are not applied immediately
[self.capturesession beginconfiguration ];

[self.capturesession removeinput:capturedeviceinput]; //remove current
[self.capturesession addinput:newinput]; //add new

// changes take effect once the outermost commitconfiguration is invoked.
[self.capturesession commitconfiguration];
break ;
}
}
}


上面的代码是使用前置摄像头和后置摄像头!