SwiftUI masking gradient with UIImage

Solution 1:

The generated qrCodeImage has no transparency (as you expected) but black& white, so it is just needed to convert it additionally into mask.

Tested with Xcode 13.2 / iOS 15.2

demo

Here is fixed part of code:

func generateQRCode(string: String) -> UIImage? {
    let data = Data(string.utf8)
    filter.setValue(data, forKey: "inputMessage")

    if let qrCodeImage = filter.outputImage {
        let maskFilter = CIFilter.maskToAlpha()
        maskFilter.setDefaults()
        maskFilter.setValue(qrCodeImage, forKey:"inputImage")

        if let maskImage = maskFilter.outputImage, let qrCodeCGImage = self.context.createCGImage(maskImage, from: maskImage.extent) {
            return UIImage(cgImage: qrCodeCGImage)
        }
    }

    return nil
}