- 获取带有文字的图片
1 2 3 4 5 6
| func btnPressed(_ sender: Any) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .savedPhotosAlbum present(picker, animated: true, completion: nil) }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion: nil) guard let image = (info[UIImagePickerControllerOriginalImage] as? UIImage) else { fatalError("no image") } self.btnImageView.setBackgroundImage(image, for: .normal)
var textLayers:[CAShapeLayer] = [] if let cgImage = image.cgImage { let textRecognizedRequest = VNDetectTextRectanglesRequest.init(completionHandler: { (request:VNRequest, error:Error?) in if (request.results as? [VNTextObservation]) != nil { textLayers = self.addShapesToText(obversations: request.results as! [VNTextObservation], view: self.btnImageView) for layer in textLayers { self.btnImageView.layer.addSublayer(layer) } } }) let handler = VNImageRequestHandler.init(cgImage: cgImage, options: [:]) guard let _ = try? handler.perform([textRecognizedRequest]) else { fatalError("failed") } } }
|
2.添加Layer展示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| func addShapesToText(obversations:[VNTextObservation],view:UIView) -> [CAShapeLayer] { let layers: [CAShapeLayer] = obversations.map { observation in let w = observation.boundingBox.size.width * view.bounds.width let h = observation.boundingBox.size.height * view.bounds.height let x = observation.boundingBox.origin.x * view.bounds.width let y = view.bounds.height - observation.boundingBox.origin.y * view.bounds.height - h let layer = CAShapeLayer() layer.frame = CGRect(x: x , y: y, width: w, height: h) layer.borderColor = UIColor.green.cgColor layer.borderWidth = 2 layer.cornerRadius = 3 return layer } return layers }
|
3.效果展示
Demo下载
如有任何疑问或问题请联系我:fishnewsdream@gmail.com,欢迎交流,共同提高!
Objective-C/Swift技术开发交流群201556264,讨论何种技术并不受限,欢迎各位大牛百家争鸣!
微信公众号OldDriverWeekly
,欢迎关注并提出宝贵意见
老司机iOS周报,欢迎关注或订阅
刚刚在线工作室,欢迎关注或提出建设性意见!
刚刚在线论坛, 欢迎踊跃提问或解答!
如有转载,请注明出处,谢谢!