本文实例为大家分享了iOS 10自定义相机功能的具体代码,供大家参考,具体内容如下
直接上代码
//// TGCameraVC.swift// TGPhotopicker//// Created by targetcloud on 2017/7/25.// copyright © 2017年 targetcloud. All rights reserved.//import UIKitimport AVFoundationimport Photos@available(iOS 10.0,*)class TGCameraVC: UIVIEwController { var callbackPicutureData: ((Data?) -> ())? private var device: AVCaptureDevice? private var input: AVCaptureDeviceinput? private var imageOutput: AVCapturePhotoOutput? private var session: AVCaptureSession? private var prevIEwLayer: AVCaptureVIDeoPrevIEwLayer? fileprivate var showImageContainerVIEw: UIVIEw? fileprivate var showImageVIEw: UIImageVIEw? fileprivate var picdata: Data? private var flashMode: AVCaptureFlashMode = .auto private weak var flashbutton: UIbutton? overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() setupCamera() setupUI() if #available(iOS 9.0,*) { let isVCBased = Bundle.main.infoDictionary?["UIVIEwControllerBasedStatusBarappearance"] as? Bool ?? false if !isVCBased{ UIApplication.shared.setStatusbarHIDden(false,with: .none) } }else { UIApplication.shared.statusbarStyle = .lightContent UIApplication.shared.setStatusbarHIDden(false,with: .none) } } overrIDe var prefeRSStatusbarHIDden: Bool{ return false } overrIDe var preferredStatusbarStyle: UIStatusbarStyle { return .lightContent } private func setupCamera() { AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVIDeo) { success in if !success { let alertVC = UIAlertController(Title: TGPhotopickerConfig.shared.cameraUsage,message: TGPhotopickerConfig.shared.cameraUsageTip,preferredStyle: .actionSheet) alertVC.addAction(UIAlertAction(Title: TGPhotopickerConfig.shared.confirmTitle,style: .default,handler: nil)) self.present(alertVC,animated: true,completion: nil) } } device = cameraWithPosistion(.back) input = try? AVCaptureDeviceinput(device: device) guard input != nil else { return } imageOutput = AVCapturePhotoOutput() session = AVCaptureSession() session?.beginConfiguration() session?.sessionPreset = TGPhotopickerConfig.shared.sessionPreset if session!.canAddinput(input) { session!.addinput(input) } if session!.canAddOutput(imageOutput) { session!.addOutput(imageOutput) } prevIEwLayer = AVCaptureVIDeoPrevIEwLayer(session: session) prevIEwLayer?.frame = vIEw.bounds prevIEwLayer?.vIDeoGravity = TGPhotopickerConfig.shared.vIDeoGravity vIEw.layer.addSublayer(prevIEwLayer!) session?.commitConfiguration() session?.startRunning() } private func cameraWithPosistion(_ position: AVCaptureDeviceposition) -> AVCaptureDevice { let type = AVCaptureDeviceType(rawValue: TGPhotopickerConfig.shared.captureDeviceType.rawValue) return AVCaptureDevice.defaultDevice(withDeviceType: type,mediaType: AVMediaTypeVIDeo,position: position) } private func setupUI() { let takebutton = UIbutton(frame: CGRect(x: 0,y: 0,wIDth: TGPhotopickerConfig.shared.takeWH,height: TGPhotopickerConfig.shared.takeWH)) takebutton.center = CGPoint(x: UIScreen.main.bounds.wIDth / 2,y: UIScreen.main.bounds.height - TGPhotopickerConfig.shared.buttonEdge.bottom) takebutton.setimage(UIImage.size(wIDth: TGPhotopickerConfig.shared.takeWH,height: TGPhotopickerConfig.shared.takeWH).border(wIDth: 3).border(color: .white).color(.clear).corner(radius: TGPhotopickerConfig.shared.takeWH / 2).image + UIImage.size(wIDth: TGPhotopickerConfig.shared.takeWH - 10,height: TGPhotopickerConfig.shared.takeWH - 10).color(UIcolor(white: 0.95,Alpha: 1) ).corner(radius: (TGPhotopickerConfig.shared.takeWH - 10) / 2).image,for: .normal) takebutton.setimage(UIImage.size(wIDth: TGPhotopickerConfig.shared.takeWH,height: TGPhotopickerConfig.shared.takeWH - 10).color(UIcolor(white: 0.8,for: .highlighted) takebutton.addTarget(self,action: #selector(takePhotoAction),for: .touchUpInsIDe) vIEw.addSubvIEw(takebutton) let cameraChangebutton = UIbutton(frame: CGRect(x: 0,wIDth: TGPhotopickerConfig.shared.takeWH * 0.6,height: TGPhotopickerConfig.shared.takeWH * 0.6)) cameraChangebutton.setimage(TGPhotopickerConfig.getimageNo2x3xSuffix("camera"),for: .normal) cameraChangebutton.center = CGPoint(x: UIScreen.main.bounds.wIDth - TGPhotopickerConfig.shared.buttonEdge.right,y: takebutton.center.y) cameraChangebutton.addTarget(self,action: #selector(changeCamerapositionAction),for: .touchUpInsIDe) cameraChangebutton.contentMode = .scaleAspectFit vIEw.addSubvIEw(cameraChangebutton) let flashChangebutton = UIbutton(frame: CGRect(x: 0,wIDth: TGPhotopickerConfig.shared.takeWH * 0.5,height: TGPhotopickerConfig.shared.takeWH * 0.5)) flashChangebutton.center = CGPoint(x: cameraChangebutton.center.x,y: TGPhotopickerConfig.shared.buttonEdge.top) flashChangebutton.setimage(TGPhotopickerConfig.getimageNo2x3xSuffix("flashauto"),for: .normal) flashChangebutton.addTarget(self,action: #selector(flashChangeAction),for: .touchUpInsIDe) flashChangebutton.contentMode = .scaleAspectFit flashbutton = flashChangebutton vIEw.addSubvIEw(flashChangebutton) let backbutton = UIbutton(frame: CGRect(x: 0,wIDth: TGPhotopickerConfig.shared.takeWH * 0.4,height: TGPhotopickerConfig.shared.takeWH * 0.4)) backbutton.center = CGPoint(x: TGPhotopickerConfig.shared.buttonEdge.left,y: flashChangebutton.center.y) backbutton.setimage(UIImage.size(wIDth: TGPhotopickerConfig.shared.takeWH * 0.4,height: TGPhotopickerConfig.shared.takeWH * 0.4) .corner(radius: TGPhotopickerConfig.shared.takeWH * 0.2) .color(.clear) .border(color: UIcolor.white.withAlphaComponent(0.7)) .border(wIDth: TGPhotopickerConfig.shared.isShowborder ? TGPhotopickerConfig.shared.checkBoxlineW : 0) .image .with({ context in context.setlineCap(.round) UIcolor.white.setstroke() context.setlinewidth(TGPhotopickerConfig.shared.checkBoxlineW) let WH = TGPhotopickerConfig.shared.takeWH * 0.4 context.move(to: CGPoint(x: WH * 0.6,y: WH * 0.2)) context.addline(to: CGPoint(x: WH * 0.35,y: WH * 0.5)) context.move(to: CGPoint(x: WH * 0.35,y: WH * 0.5)) context.addline(to: CGPoint(x: WH * 0.6,y: WH * 0.8)) context.strokePath() }),for: .normal) backbutton.contentMode = .scaleAspectFit backbutton.addTarget(self,action: #selector(backAction),for: .touchUpInsIDe) vIEw.addSubvIEw(backbutton) showImageContainerVIEw = UIVIEw(frame: vIEw.bounds) showImageContainerVIEw?.backgroundcolor = TGPhotopickerConfig.shared.prevIEwBGcolor vIEw.addSubvIEw(showImageContainerVIEw!) let height = showImageContainerVIEw!.bounds.height - TGPhotopickerConfig.shared.takeWH - TGPhotopickerConfig.shared.buttonEdge.bottom - TGPhotopickerConfig.shared.prevIEwpadding * 2 showImageVIEw = UIImageVIEw(frame: CGRect(x: TGPhotopickerConfig.shared.prevIEwpadding,y: TGPhotopickerConfig.shared.prevIEwpadding * 2,wIDth: showImageContainerVIEw!.bounds.wIDth - 2 * TGPhotopickerConfig.shared.prevIEwpadding,height: height)) showImageVIEw?.contentMode = .scaleAspectFit showImageContainerVIEw?.addSubvIEw(showImageVIEw!) showImageContainerVIEw?.isHIDden = true let giveupbutton = createImageOperatorbutton(nil,CGPoint(x: TGPhotopickerConfig.shared.takeWH * 1.5,y: showImageContainerVIEw!.bounds.height - TGPhotopickerConfig.shared.takeWH * 1.5),TGPhotopickerConfig.shared.getCheckBoxImage(true,true,.circle,TGPhotopickerConfig.shared.takeWH * 0.7).unselect) giveupbutton.addTarget(self,action: #selector(giveupImageAction),for: .touchUpInsIDe) showImageContainerVIEw?.addSubvIEw(giveupbutton) let ensurebutton = createImageOperatorbutton(nil,CGPoint(x: showImageContainerVIEw!.bounds.wIDth - TGPhotopickerConfig.shared.takeWH * 1.5,false,TGPhotopickerConfig.shared.takeWH * 0.7).select) ensurebutton.addTarget(self,action: #selector(useImageAction),for: .touchUpInsIDe) showImageContainerVIEw?.addSubvIEw(ensurebutton) } private func createImageOperatorbutton(_ Title: String?,_ center: CGPoint,_ img: UIImage?) -> UIbutton { let btn = UIbutton(frame: CGRect(x: 0,wIDth: TGPhotopickerConfig.shared.takeWH * 0.7,height: TGPhotopickerConfig.shared.takeWH * 0.7)) btn.center = center btn.setTitle(Title,for: .normal) btn.setimage(img,for: .normal) btn.contentMode = .scaleAspectFit return btn } @objc private func flashChangeAction() { switch flashMode { case .auto: flashMode = .on flashbutton?.setimage(TGPhotopickerConfig.getimageNo2x3xSuffix("flash"),for: .normal) case .on: flashMode = .off flashbutton?.setimage(TGPhotopickerConfig.getimageNo2x3xSuffix("flashno"),for: .normal) case .off: flashMode = .auto flashbutton?.setimage(TGPhotopickerConfig.getimageNo2x3xSuffix("flashauto"),for: .normal) } } @objc private func backAction() { dismiss(animated: true,completion: nil) } @objc private func takePhotoAction() { let connection = imageOutput?.connection(withMediaType: AVMediaTypeVIDeo) guard connection != nil else { return } let photoSettings = AVCapturePhotoSettings() photoSettings.flashMode = flashMode imageOutput?.capturePhoto(with: photoSettings,delegate: self) } @objc private func changeCamerapositionAction() { let animation = CATransition() animation.duration = 0.5 animation.timingFunction = camediatimingFunction(name: kcamediatimingFunctionEaseInEaSEOut) animation.type = TGPhotopickerConfig.shared.TransitionType let newDevice: AVCaptureDevice! let newinput: AVCaptureDeviceinput? let position = input?.device.position if position == .front { newDevice = cameraWithPosistion(.back) animation.subtype = kCATransitionFromleft } else { newDevice = cameraWithPosistion(.front) animation.subtype = kCATransitionFromright } newinput = try? AVCaptureDeviceinput(device: newDevice) guard newinput != nil else{ return } prevIEwLayer?.add(animation,forKey: nil) session?.beginConfiguration() session?.removeinput(input) if session!.canAddinput(newinput) { session?.addinput(newinput!) input = newinput } else { session?.addinput(input) } session?.commitConfiguration() } @objc private func giveupImageAction() { showImageVIEw?.image = UIImage() showImageContainerVIEw?.isHIDden = true } @objc private func useImageAction() { callbackPicutureData?(picdata) dismiss(animated: true,completion: nil) }}@available(iOS 10.0,*)extension TGCameraVC: AVCapturePhotoCaptureDelegate { func capture(_ captureOutput: AVCapturePhotoOutput,dIDFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?,prevIEwPhotoSampleBuffer: CMSampleBuffer?,resolvedSettings: AVCaptureResolvedPhotoSettings,bracketSettings: AVCaptureBracketedStillimagesettings?,error: Error?) { if error != nil { print("error = \(String(describing: error?.localizedDescription))") } else { if let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer!,prevIEwPhotoSampleBuffer: prevIEwPhotoSampleBuffer){ picdata = imageData showImageContainerVIEw?.isHIDden = false showImageVIEw?.image = UIImage(data: imageData) if TGPhotopickerConfig.shared.saveImagetoPhotoAlbum{ self.saveImagetoPhotoAlbum(UIImage(data: imageData)!) } } } } fileprivate func saveImagetoPhotoAlbum(_ savedImage:UIImage){ UIImageWritetoSavedPhotosAlbum(savedImage,self,#selector(imageDIDFinishSavingWithErrorContextInfo),nil) } @objc fileprivate func imageDIDFinishSavingWithErrorContextInfo(image:UIImage,error:NSError?,contextInfo:UnsafeMutableRawPointer?){ if canUseAlbum(){ let msg = (error != nil) ? TGPhotopickerConfig.shared.saveImageFailTip : TGPhotopickerConfig.shared.saveImageSuccesstip let alert = UIAlertVIEw(Title: TGPhotopickerConfig.shared.saveImageTip,message: msg,delegate: self,cancelbuttonTitle: TGPhotopickerConfig.shared.confirmTitle) alert.show() } } fileprivate func canUseAlbum()-> Bool{ if PHPhotolibrary.authorizationStatus() != PHAuthorizationStatus.authorized { let alertVIEw = UIAlertVIEw(Title: TGPhotopickerConfig.shared.PhotolibraryUsage,message: TGPhotopickerConfig.shared.PhotolibraryUsageTip,delegate: nil,cancelbuttonTitle: TGPhotopickerConfig.shared.confirmTitle,otherbuttonTitles: TGPhotopickerConfig.shared.cancelTitle) alertVIEw.tag = TGPhotopickerConfig.shared.alertVIEwTag alertVIEw.show() return false }else{ return true } }}
效果如下
完整使用DEMO见:点击打开链接
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
总结以上是内存溢出为你收集整理的iOS 10自定义相机功能全部内容,希望文章能够帮你解决iOS 10自定义相机功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)