[英]ImageAnalysisInteraction in UIViewRepresentable not working correctly
I have a simple UIViewRepresentable
wrapper for the live text feature ( ImageAnalysisInteraction
).我有一个用于实时文本功能 ( ImageAnalysisInteraction
) 的简单UIViewRepresentable
包装器。 It was working without issues until I started updating the UIImage
inside the updateUIView(...)
function.在我开始更新updateUIView(...)
function 中的UIImage
之前,它一直没有问题。
I have always been seeing this error in the console which originates from this view: [api] -[CIImage initWithCVPixelBuffer:options:] failed because the buffer is nil.
我一直在控制台中看到源自此视图的此错误: [api] -[CIImage initWithCVPixelBuffer:options:] failed because the buffer is nil.
When I change the image, it's updating correctly, but the selectableItemsHighlighted
overlay stays the same and I can still select the text of the old image (even though it's no longer visible).当我更改图像时,它会正确更新,但selectableItemsHighlighted
叠加层保持不变,我仍然可以 select 旧图像的文本(即使它不再可见)。
import UIKit
import SwiftUI
import VisionKit
@MainActor
struct LiveTextInteraction: UIViewRepresentable {
@Binding var image: UIImage
let interaction = ImageAnalysisInteraction()
let imageView = LiveTextImageView()
let analyzer = ImageAnalyzer()
let configuration = ImageAnalyzer.Configuration([.text])
func makeUIView(context: Context) -> UIImageView {
interaction.setSupplementaryInterfaceHidden(true, animated: true)
imageView.image = image
imageView.addInteraction(interaction)
imageView.contentMode = .scaleAspectFit
return imageView
}
func updateUIView(_ uiView: UIImageView, context: Context) {
Task {
uiView.image = image
do {
if let image = uiView.image {
let analysis = try await analyzer.analyze(image, configuration: configuration)
interaction.analysis = analysis;
interaction.preferredInteractionTypes = .textSelection
interaction.selectableItemsHighlighted = true
interaction.setContentsRectNeedsUpdate()
}
} catch {
// catch
}
}
}
}
class LiveTextImageView: UIImageView {
// Use intrinsicContentSize to change the default image size
// so that we can change the size in our SwiftUI View
override var intrinsicContentSize: CGSize {
.zero
}
}
What am I doing wrong here?我在这里做错了什么?
It looks like a bug.它看起来像一个错误。 Try use dispatch尝试使用调度
let highlighted = interaction.selectableItemsHighlighted
interaction.analysis = analysis // highlighted == false
if highlighted
{
DispatchQueue.main.async
{
interaction.selectableItemsHighlighted = highlighted
}
}
You don't need interaction.setContentsRectNeedsUpdate()
if the interaction is added to a UIImageView如果将交互添加到 UIImageView,则不需要interaction.setContentsRectNeedsUpdate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.