我是swift的新手,我想做一个可以解析截图的应用程序。到目前为止,我有下面的代码,我无法找出正确的方法来调用我的ContentView中的识别功能,任何帮助都是感激之情:'
struct ContentView: View {
@State var selectedItems: PhotosPickerItem?
@State var selectedPhotoData: Data?
func recogText(selData: Data?)
{
if let selData = selData, let image = UIImage(data: selData){
guard let cgImage = image.cgImage else {return}
let handler = VNImageRequestHandler(cgImage: cgImage)
let request = VNDetectTextRectanglesRequest { request, error in
guard let observations = request.results as? [VNRecognizedTextObservation],
error == nil else {return}
let text = observations.compactMap({
$0.topCandidates(1).first?.string
}).joined(separator: ", ")
print(text.count)
}
do {
try handler.perform([request])
}
catch {
print("Unable to perform the requests: \(error).")
}
}
}
var body: some View {
VStack{
//Icon
mainImage()
//Button
PhotosPicker(selection: $selectedItems, matching: .images) {
Label("Select a photo", systemImage: "photo")
}
.tint(.blue)
.controlSize(.large)
.buttonStyle(.borderedProminent)
.onChange(of: selectedItems) { newItem in
Task {
if let data = try? await newItem?.loadTransferable(type: Data.self) {
selectedPhotoData = data
let _ = recogText(selData: data)
}
}
}
}
}
}
'
应打印已分析的文本,但未找到输出
1条答案
按热度按时间xzv2uavs1#
你好,这里是一个示例函数,可能会对你有所帮助。当然,你必须用你的图像替换TestImage。这可能对你有用,你需要导入Vision