自定义蒙层相机"/>
swift 自定义蒙层相机
直接上效果
自定义相机这个就没得说了集成的AVFoundation 百度都有
直接说蒙层吧
//绘制遮罩层
func drawCoverView() {let view = UIView(frame: self.view.bounds)view.backgroundColor = .blackview.alpha = 0.5self.view.addSubview(view)let bpath = UIBezierPath(roundedRect: self.view.bounds,cornerRadius: 0)let bpath2 = UIBezierPath(roundedRect: CGRect(x: horizontally(viewWidth: photoWidth), y: verticalCentralization(viewHeight: photoHeigth), width: photoWidth, height: photoHeigth), cornerRadius: 0)bpath.append(bpath2.reversing())let shapeLayer = CAShapeLayer.init()shapeLayer.path = bpath.cgPathview.layer.mask = shapeLayer}
关键点
创建一个全屏view
bpath 先绘制一个全屏的蒙层
bpath2 通过reversing()方法反向绘制透明的款
这个是最简单粗暴的玩法
import UIKit
import AVFoundationclass ScannerVC: UIViewController {var back_but:UIButton?var photoBut:UIButton?var lightBut:UIButton?var callback: ((UIImage)->Void)?////捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)var device:AVCaptureDevice?//AVCaptureDeviceInput 代表输入设备,他使用AVCaptureDevice 来初始化var input:AVCaptureDeviceInput?//当启动摄像头开始捕获输入var output:AVCaptureMetadataOutput?var ImageOutPut:AVCaptureStillImageOutput?//session:由他把输入输出结合在一起,并开始启动捕获设备(摄像头)var session:AVCaptureSession?//图像预览层,实时显示捕获的图像var previewLayer:AVCaptureVideoPreviewLayer?var canCa = falsevar imageView:UIImageView?var image:UIImage?var maskLayer:CAShapeLayer?//半透明黑色遮罩var effectiveRectLayer: CAShapeLayer?//有效区域框var photoWidth = K_Screen_width-40var photoHeigth = Int(Double(K_Screen_width-40) / 1.6)var focusView: UIView? //聚焦var isLightOn = falseoverride func viewDidLoad() {super.viewDidLoad()self.view.backgroundColor = .blackdrawCoverView()createView()canCa = canUserCamear()if(canCa){customUI()customCamera()}}//绘制遮罩层func drawCoverView() {let view = UIView(frame: self.view.bounds)view.backgroundColor = .blackview.alpha = 0.5self.view.addSubview(view)let bpath = UIBezierPath(roundedRect: self.view.bounds,cornerRadius: 0)let bpath2 = UIBezierPath(roundedRect: CGRect(x: horizontally(viewWidth: photoWidth), y: verticalCentralization(viewHeight: photoHeigth), width: photoWidth, height: photoHeigth), cornerRadius: 0)bpath.append(bpath2.reversing())let shapeLayer = CAShapeLayer.init()shapeLayer.path = bpath.cgPathview.layer.mask = shapeLayer}//设置聚焦func customUI(){focusView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))focusView?.layer.borderWidth = 1.0focusView?.layer.borderColor = UIColor.green.cgColorfocusView?.backgroundColor = .clearfocusView?.isHidden = trueself.view.addSubview(focusView!)
// 设置手势let tapGesture = UITapGestureRecognizer(target: self, action: #selector(focusGesture(gesture:)))self.view.addGestureRecognizer(tapGesture)}@objc func focusGesture(gesture:UITapGestureRecognizer){let point = gesture.location(in: gesture.view)focusAtPoint(point: point)}func focusAtPoint(point:CGPoint){let size = self.view.bounds.sizelet focusPorint = CGPoint(x: point.y / size.height, y: 1-point.x/size.width)do{try device?.lockForConfiguration()//焦点if((self.device?.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus))!){self.device?.focusPointOfInterest = focusPorintself.device?.focusMode = AVCaptureDevice.FocusMode.autoFocus}//曝光if((self.device?.isExposureModeSupported(AVCaptureDevice.ExposureMode.autoExpose))!){self.device?.exposurePointOfInterest = focusPorintself.device?.exposureMode = AVCaptureDevice.ExposureMode.autoExpose}self.device?.unlockForConfiguration()focusView?.center = pointfocusView?.isHidden = falseUIView.animate(withDuration: 0.3, animations: {self.focusView?.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)}) { (finished) inUIView.animate(withDuration: 0.5, animations: {self.focusView?.transform = CGAffineTransform.identity}, completion: { (finished) inself.focusView?.isHidden = true})}}catch{return}}//相机初始化func customCamera() {maskLayer = CAShapeLayer.init()self.view.backgroundColor = .white// 使用AVMediaTypeVideo 指明self.device代表视频,默认使用后置摄像头进行初始化self.device = AVCaptureDevice.default(for: AVMediaType.video)//使用设备初始化输入do {self.input = try AVCaptureDeviceInput(device: self.device!)}catch {print(error)return}
// self.input = AVCaptureDeviceInput.init(device: self.device!)//生成输出对象self.output = AVCaptureMetadataOutput.init()self.ImageOutPut = AVCaptureStillImageOutput.init()//生成会话,用来结合输入输出self.session = AVCaptureSession.init()if((self.session?.canSetSessionPreset(AVCaptureSession.Preset.hd1920x1080))!){self.session?.sessionPreset = AVCaptureSession.Preset.hd1920x1080;}if(self.session!.canAddInput(self.input!)){self.session!.addInput(self.input!)}if(self.session!.canAddOutput(self.ImageOutPut!)){self.session!.addOutput(self.ImageOutPut!)}//使用self.session,初始化预览层,self.session负责驱动input进行信息的采集,layer负责把图像渲染显示self.previewLayer = AVCaptureVideoPreviewLayer.init(session: session!)self.previewLayer?.frame = CGRect(x: 0, y: 0, width: K_Screen_width, height: K_Screen_height)self.previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFillself.view.layer.insertSublayer(self.previewLayer!, at: 0)//开始启动self.session?.startRunning()do{if(try self.device?.lockForConfiguration() == nil && self.device!.isFlashModeSupported(AVCaptureDevice.FlashMode.auto)){self.device?.flashMode = AVCaptureDevice.FlashMode.auto}}catch{print(error)}//自动白平衡if(self.device!.isWhiteBalanceModeSupported(AVCaptureDevice.WhiteBalanceMode.autoWhiteBalance)){self.device?.whiteBalanceMode = AVCaptureDevice.WhiteBalanceMode.autoWhiteBalance}else{self.device?.unlockForConfiguration()}}func createView() {let topHight = Int(barHeight) + Int((self.navigationController?.navigationBar.frame.size.height)!);back_but = UIButton(type: .custom);let back=UIImage(named: "white_black");back_but?.frame = CGRect(x: 20, y: CGFloat(topHight/2), width: (back?.size.width)!, height: (back?.size.height)!)back_but?.addTarget(self, action: #selector(backPage), for: .touchUpInside)back_but?.setBackgroundImage(back, for: .normal)photoBut = UIButton.init()photoBut?.addTarget(self, action: #selector(shutterCamera), for: .touchUpInside)photoBut?.setBackgroundImage(UIImage(named: "startBtn"), for: .normal)photoBut?.frame = CGRect(x: horizontally(viewWidth: 70), y:bottomY - 70, width: 70, height:70)
// photoBut?.layer.cornerRadius = 35self.view.addSubview(photoBut!)self.view.addSubview(back_but!)let labele = UILabel();let width1 = ga_widthForComment(str: "请将身份证正面置入框中,注意光线", fontSize: 16)let height1 = ga_heightForComment(str: "请将身份证正面置入框中,注意光线", fontSize: 16, width: width1)labele.frame = CGRect(x: horizontally(viewWidth: Int(width1)), y: Int(K_Screen_height/2) - (photoHeigth/2) - Int(height1+10), width: Int(width1), height: Int(height1))labele.text = "请将身份证正面置入框中,注意光线"labele.textColor = .whitelabele.font=UIFont.systemFont(ofSize: 16)self.view.addSubview(labele)let width2 = ga_widthForComment(str: "闪光灯", fontSize: 16)let height2 = ga_heightForComment(str: "闪光灯", fontSize: 16, width: width1)lightBut = UIButton(frame: CGRect(x: CGFloat(K_Screen_width - Int(20 + width2)), y: CGFloat(topHight/2), width: width2, height: height2))lightBut?.setTitle("闪光灯", for: .normal)
// lightBut?.titleLabel?.textColor = .groupTableViewBackgroundlightBut?.setTitleColor(.groupTableViewBackground, for: .normal)lightBut?.titleLabel?.font = UIFont.systemFont(ofSize: 16)lightBut?.addTarget(self, action: #selector(light), for: .touchUpInside)self.view.addSubview(lightBut!)//边框线条。startlet view2 = UIView(frame:CGRect(x: 18, y: Int(K_Screen_height/2) - (photoHeigth/2) - 4, width: 32, height: 2))view2.backgroundColor = .whiteself.view.addSubview(view2)let view3 = UIView(frame:CGRect(x: K_Screen_width - 50, y: Int(K_Screen_height/2) - (photoHeigth/2) - 4, width: 32, height: 2))view3.backgroundColor = .whiteself.view.addSubview(view3)let view4 = UIView(frame:CGRect(x: 18, y: Int(K_Screen_height/2) + (photoHeigth/2) + 2, width: 32, height: 2))view4.backgroundColor = .whiteself.view.addSubview(view4)let view5 = UIView(frame:CGRect(x: K_Screen_width - 50, y: Int(K_Screen_height/2) + (photoHeigth/2) + 2, width: 32, height: 2))view5.backgroundColor = .whiteself.view.addSubview(view5)let view6 = UIView(frame:CGRect(x: 16, y: Int(K_Screen_height/2) - (photoHeigth/2)-4, width: 2, height: 32))view6.backgroundColor = .whiteself.view.addSubview(view6)let view7 = UIView(frame:CGRect(x: K_Screen_width - 18, y: Int(K_Screen_height/2) - (photoHeigth/2)-4, width: 2, height: 32))view7.backgroundColor = .whiteself.view.addSubview(view7)let view8 = UIView(frame:CGRect(x: 16, y: Int(K_Screen_height/2) + (photoHeigth/2)-28, width: 2, height: 32))view8.backgroundColor = .whiteself.view.addSubview(view8)let view9 = UIView(frame:CGRect(x: K_Screen_width - 18, y: Int(K_Screen_height/2) + (photoHeigth/2)-28, width: 2, height: 32))view9.backgroundColor = .whiteself.view.addSubview(view9)//--end---}@objc func backPage(){self.navigationController?.popViewController(animated: true);}//相机权限func canUserCamear() -> Bool {let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)if(authStatus == AVAuthorizationStatus.denied){
// let alertView = UIAlertView.init(title: "请打开相机权限", message: "设置-隐私-相机", delegate: self, cancelButtonTitle: "确定",otherButtonTitles: "取消");
// alertView.show()let alertController = UIAlertController(title: " 请打开相机权限", message: "设置-隐私-相机", preferredStyle: .alert)let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) inself.backPage()}let okAction = UIAlertAction(title: "确定", style: .default) { (UIAlertAction) inlet url = URL(string: UIApplication.openSettingsURLString)if (UIApplication.shared.canOpenURL(url!)){UIApplication.shared.openURL(url!)}}alertController.addAction(cancelAction)alertController.addAction(okAction)self.present(alertController, animated: true, completion: nil)return false}else{return true}return true}@objc func light(){do{try device?.lockForConfiguration()if(!isLightOn){device?.torchMode = AVCaptureDevice.TorchMode.onisLightOn = true
// self.lightBut?.titleLabel?.textColor = .greenlightBut?.setTitleColor(.green, for: .normal)}else{device?.torchMode = AVCaptureDevice.TorchMode.offisLightOn = false
// self.lightBut?.titleLabel?.textColor = .groupTableViewBackgroundlightBut?.setTitleColor(.groupTableViewBackground, for: .normal)}device?.unlockForConfiguration()}catch{return}}@objc func shutterCamera(){let videoConnection = self.ImageOutPut?.connection(with: AVMediaType.video)videoConnection?.videoOrientation = AVCaptureVideoOrientation.portraitif(!(videoConnection != nil)){return}self.ImageOutPut?.captureStillImageAsynchronously(from: videoConnection!, completionHandler: { (imageDataSampleBuffer, error) inif(imageDataSampleBuffer == nil){return}let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)self.image = UIImage.init(data: imageData!)self.session?.stopRunning()//计算比例let aspectWidth = self.image!.size.width / CGFloat(K_Screen_width)let aspectHeight = self.image!.size.height / CGFloat(K_Screen_height)
// 图片绘制区域var scaledImageRect = CGRect.zeroscaledImageRect.size.width = CGFloat(self.photoWidth) * CGFloat(aspectWidth)scaledImageRect.size.height = CGFloat(self.photoHeigth) * CGFloat(aspectHeight)scaledImageRect.origin.x = CGFloat(horizontally(viewWidth: self.photoWidth)) * CGFloat(aspectWidth)scaledImageRect.origin.y = CGFloat(verticalCentralization(viewHeight: self.photoHeigth)) * CGFloat(aspectHeight)let i = self.imageFromImage(image: self.fixOrientation(image: self.image!), rect: scaledImageRect)self.imageView = UIImageView(frame: CGRect(x: horizontally(viewWidth: self.photoWidth), y: verticalCentralization(viewHeight: self.photoHeigth), width: self.photoWidth, height: self.photoHeigth))self.imageView?.contentMode = UIView.ContentMode.scaleAspectFill
// self.view.insertSubview(self.imageView!, belowSubview: but)self.imageView?.layer.masksToBounds = trueself.imageView?.image = iself.callback?(i)self.backPage()
// self.view.addSubview(self.imageView!)})}func scaled(to newSize: CGSize,size:CGSize) -> UIImage {//计算比例let aspectWidth = newSize.width/size.widthlet aspectHeight = newSize.height/size.heightlet aspectRatio = max(aspectWidth, aspectHeight)//图片绘制区域var scaledImageRect = CGRect.zeroscaledImageRect.size.width = size.width * aspectRatioscaledImageRect.size.height = size.height * aspectRatioscaledImageRect.origin.x = 0scaledImageRect.origin.y = 0//绘制并获取最终图片UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)//图片不失真
// drem(in: scaledImageRect)let scaledImage = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsEndImageContext()return scaledImage!}/***从图片中按指定的位置大小截取图片的一部分* UIImage image 原始的图片* CGRect rect 要截取的区域*/func imageFromImage(image:UIImage,rect:CGRect) -> UIImage {//将UIImage转换成CGImageReflet sourceImageRef = image.cgImage//按照给定的矩形区域进行剪裁let newImageRef = sourceImageRef?.cropping(to: rect)let newImage = UIImage.init(cgImage: newImageRef!)return newImage}// //按下的效果
// -(void)touchDown{
// self.saveBtn.backgroundColor = [UIColor colorFromHexValue:0x9B0000];
// }
//
// //按下拖出按钮松手还原
// -(void)touchUpOutside{
// self.saveBtn.backgroundColor = [UIColor colorFromHexValue:0xFF2741];
// }func fixOrientation(image:UIImage) -> UIImage {if image.imageOrientation == .up {return image}var transform = CGAffineTransform.identityswitch image.imageOrientation {case .down, .downMirrored:transform = transform.translatedBy(x: image.size.width, y: image.size.height)transform = transform.rotated(by: .pi)breakcase .left, .leftMirrored:transform = transform.translatedBy(x: image.size.width, y: 0)transform = transform.rotated(by: .pi / 2)breakcase .right, .rightMirrored:transform = transform.translatedBy(x: 0, y: image.size.height)transform = transform.rotated(by: -.pi / 2)breakdefault:break}switch image.imageOrientation {case .upMirrored, .downMirrored:transform = transform.translatedBy(x: image.size.width, y: 0)transform = transform.scaledBy(x: -1, y: 1)breakcase .leftMirrored, .rightMirrored:transform = transform.translatedBy(x: image.size.height, y: 0);transform = transform.scaledBy(x: -1, y: 1)breakdefault:break}let ctx = CGContext(data: nil, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: image.cgImage!.bitsPerComponent, bytesPerRow: 0, space: image.cgImage!.colorSpace!, bitmapInfo: image.cgImage!.bitmapInfo.rawValue)ctx?.concatenate(transform)switch image.imageOrientation {case .left, .leftMirrored, .right, .rightMirrored:ctx?.draw(image.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(image.size.height), height: CGFloat(image.size.width)))breakdefault:ctx?.draw(image.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(image.size.width), height: CGFloat(image.size.height)))break}let cgimg: CGImage = (ctx?.makeImage())!let img = UIImage(cgImage: cgimg)return img}
}
跳转到这个相机页面并返回中间的图片
let vc = ScannerVC()vc.callback = { image inprint(image)self.idImage = image}self.navigationController?.pushViewController(vc, animated: true);
额外说一个坑 自定义相机拍的照片 赋到imageview 是正常的 时间上是旋转了90度的 裁剪区域图片要注意下 fixOrientation这个方法是处理了旋转图片的
如果这个文章对你有帮助就点下赞吧
源码地址
更多推荐
swift 自定义蒙层相机
发布评论