美文网首页优秀的Objective-C第三方库转Swift
Swift4.2 自定义相机:身份证拍照

Swift4.2 自定义相机:身份证拍照

作者: 船长_ | 来源:发表于2018-11-15 16:16 被阅读26次

    效果图:


    E7559627F62BB00925EAD4E1CDAA9C6A.jpg

    使用示例

    / 身份证正面
    @IBAction func frontClick(_ sender: Any) {
        let vc = DXIDCardCameraController.init(type: DXIDCardType.front)
        vc.delegate = self
        self.present(vc, animated: true, completion: nil)
    }
    
    // 身份证反面
    @IBAction func reverseClick(_ sender: Any) {
        let vc = DXIDCardCameraController.init(type: DXIDCardType.reverse)
        vc.delegate = self
        self.present(vc, animated: true, completion: nil)
    }
    
    
    extension ViewController : DXIDCardCameraControllerProtocol {
        func cameraDidFinishShootWithCameraImage(image: UIImage) {
            self.imageView.image = image
        }
    }
    

    核心代码1:拍完照,沿着框框把图片进行裁剪,并修改了图片的方向

    public func dx_clipImageInRect(rect: CGRect) -> UIImage?{
       
        let widthScale : CGFloat = self.size.width / kScreenW
        let heightScale : CGFloat = self.size.height / kScreenH
        
        //其实是横屏的
        let originWidth : CGFloat = rect.size.width
        let originHeight : CGFloat = rect.size.height
        
        
        let x : CGFloat = (kScreenH - originHeight) * 0.5 * heightScale
        let y : CGFloat = (kScreenW - originWidth) * 0.5 * widthScale
        let width : CGFloat = originHeight * heightScale
        let height : CGFloat = originWidth * widthScale
        
        let r : CGRect = CGRect.init(x: x, y: y, width: width, height: height)
        if let cgImg = self.cgImage?.cropping(to: r) {
            return UIImage.init(cgImage: cgImg, scale: 1.0, orientation: UIImage.Orientation.right)
        }
    
        return nil
    }
    

    真正使用照片的时候,再次修改照片的方向

    let newImg = UIImage.init(cgImage: cgImg, scale: 1.0, orientation: UIImage.Orientation.up)
    

    亮点:自动对焦,点击屏幕聚焦

    @objc private func focusAtPoint(point : CGPoint) {
        let size = view.bounds.size
        let focusPoint = CGPoint.init(x: point.y/size.height, y: 1-point.x/size.width)
        if let device = device {
            do {
                try device.lockForConfiguration()
                if device.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus) {
                    device.focusPointOfInterest = focusPoint
                    device.focusMode = .autoFocus
                }
                if device.isExposureModeSupported(AVCaptureDevice.ExposureMode.autoExpose){
                    device.exposurePointOfInterest = focusPoint
                    device.exposureMode = .autoExpose
                }
                device.unlockForConfiguration()
            } catch let error {
                print(error)
            }
        }
    }
    

    demo下载连接
    Objective-C版本下载连接

    相关文章

      网友评论

        本文标题:Swift4.2 自定义相机:身份证拍照

        本文链接:https://www.haomeiwen.com/subject/novyfqtx.html