I use this code to show the Image in HDR in SwiftUI
struct HDRImageView: UIViewRepresentable {
// Set up a common reader for all UIImage read requests.
static let reader: UIImageReader = {
var config = UIImageReader.Configuration()
config.prefersHighDynamicRange = true
return UIImageReader(configuration: config)
}()
let data:Data?
let enableHDR:Bool
func makeUIView(context: Context) -> UIImageView {
let view = UIImageView()
view.preferredImageDynamicRange = enableHDR ? .high : .standard
update(view)
// Set this view to fit itself to the parent view.
view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
view.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
view.setContentHuggingPriority(.required, for: .horizontal)
view.setContentHuggingPriority(.required, for: .vertical)
return view
}
func updateUIView(_ view: UIImageView, context: Context) {
update(view)
}
func update(_ view: UIImageView) {
autoreleasepool{//not working
if let data = data {
view.image = nil//set to nil first is not working
view.image = HDRImageView.reader.image(data: data)
} else {
view.image = nil
}
view.preferredImageDynamicRange = enableHDR ? .high : .standard
}
}
}
But when I update the input data, seems that the old image data can not be freeed. After several changes, the app takes too much memory and crash.
I found it's the VM:ImageIO_Surface_Data
and the VM_Image_IO
take up the memory.
If I change the HDRImageView
into a normal Image(uiimage:UIImage(data:))
It no longer have this issue.
Is it a memory leak? and how to solve this.
Update: I then tried using Image(_:cgImage)
, and it appear to be the same result.