WWDC21:从照片中获取文本 Text from Camera

发布
更新
字数 502
阅读 3 分钟
阅读量 941

iOS15 带来了新的 API,类似 OCR,可以使用相机实时图片中的文本,并自动填充到文本控件中。可以通过设置 UITextContentTypeUIKeyboardType ,或使用新的 Action.captureTextFromCamera(responder:, identifier:) 实现,或自定义 Image View 实现 UIKeyInput 协议。

通过设置内容过滤实现

内容过滤基于 UITextViewUITextField 均支持的属性:UITextContentTypeUIKeyboardType

支持 7 种 UITextContentType 过滤 Full street address / Telephone number / Email address / URL / Shipment tracking number / Flight number / Date time and duration

UITextContentType Example
.TelephoneNumber (808) 555-8526
.FullStreetAddress 1400 Aloha Parkway Maui, HI 96753
.URL https://swiftdict.com
.EmailAddress agaorlova@icloud.com
.FlightNumber "CA # 1234", "AA212", "SW Flight 573" New in iOS15
.ShipmentTrackingNumber 1Z50T0536891664106 New in iOS15
.DateTime "7-3-2021", "This Saturday", "12:30", "10-11am" New in iOS15

代码示例

phone.keyboardType = .phonePad
// phone.autocorrectionType = .no

address.textContentType = .fullStreetAddress

更多输入

Editing Menu

当用户再次轻触输入框时,唤起上下文菜单引导用户使用 Text from Camera

自定义 Action

let textFromCamera = UIAction.captureTextFromCamera(responder: self.notes, identifier: nil)

let choosePhotoOrVideo = UIAction(…)
let takePhotoOrVideo = UIAction(…)
let scanDocuments = UIAction(…)

let cameraMenu = UIMenu(children: [choosePhotoOrVideo, takePhotoOrVideo, scanDocuments, textFromCamera])

let menuToolbarItem = UIBarButtonItem(title: nil, image: UIImage(systemName: "camera.badge.ellipsis"), primaryAction: nil, menu: cameraMenu)

从相机捕获的文本会自动填入输入框,而且是实时的。

注意,想起他的编辑菜单如剪切、拷贝、粘贴,在使用 Camera 捕获文本特性前需要检查是否可用。因为该特性需要:

  • 2018及之后上市的 iPhone,支持 Neural Engine;
  • Responder 需要响应文本插入;
  • 使用 UITextViewUITextField 时必须可编辑;
  • 用户首选语言包含目前支持的 7 种语言:英语、法语、葡萄牙语、意大利语、德语、西班牙语以及中文
let !self.notes.canPerformAction(#selector(captureTextFromCamera(_:)), withSender: self) {
    return
}

使用 UIImageView

自定义 Image View,实现 UIKeyInput 协议 insertText(_:) 方法:

class HeadlineImageView: UIImageView, UIKeyInput {
    var headlineLabel: UILabel = UILabel()
    var hasText: Bool = false

    override init(image: UIImage?) {
        super.init(image: image)
        initializeLabel()
    }
    
    func insertText(_ text: String) {
        headlineLabel.text = text
    }

    func deleteBackward() { }
}

via WWDC 2021: Use the camera for keyboard input in your app