Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from UIImage to a SwiftUI Image results in a blank image of the same size

Tags:

uikit

swiftui

I am trying to convert a UIImage to a SwiftUI Image using the init(uiImage:) initializer. My UIImage itself is created from a CIImage generated by a CIQRCodeGenerator CIFilter. I am running my code on a Playground in Xcode 11.1 GM seed 1. Here is the entirety of my code:

import SwiftUI
import UIKit

func qrCodeImage(for string: String) -> Image? {
  let data = string.data(using: String.Encoding.utf8)
  guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
  qrFilter.setValue(data, forKey: "inputMessage")

  guard let ciImage = qrFilter.outputImage else { return nil }
  let uiImage = UIImage(ciImage: ciImage)
  let image = Image(uiImage: uiImage)

  return image
}

let image = qrCodeImage(for: "fdsa")

And here is the result:

enter image description here

Even when I transform the image with CGAffineTransform(scaleX: 10, y: 10), the resulting SwiftUI Image at the end is still the same size, but blank.

like image 368
Eugene Avatar asked Sep 24 '19 20:09

Eugene


2 Answers

Following solution provided in: Generating QR Code with SwiftUI shows empty picture

Here is the code:

var ciContext = CIContext()

func qrCodeImage(for string: String) -> Image? {
    let data = string.data(using: String.Encoding.utf8)
    guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
    qrFilter.setValue(data, forKey: "inputMessage")

    guard let ciImage = qrFilter.outputImage else { return nil }
    let cgImage = ciContext.createCGImage(ciImage, from: ciImage.extent)

    let uiImage = UIImage(cgImage: cgImage!)

    let image = Image(uiImage: uiImage)

    return image
}

 let image = qrCodeImage(for: "fdsa")

Result:

screenshot in swift playground

like image 168
wk.experimental Avatar answered Sep 21 '22 18:09

wk.experimental


Can confirm I encounter the same issue with a SwiftUI Image using a UIImage initialized from data. Can verify that the image is loaded when paused in debugging, but it does not display in the SwiftUI Image.

This solution worked for me: explicitly specify the image rendering mode. In my case I added the following: .renderingMode(.original)

like image 36
David Earnest Avatar answered Sep 18 '22 18:09

David Earnest