Why is the brightness filter between Image and CIImage different in SwiftUI?

Viewed 167

I'm adjusting the brightness of an image.

First I used SwiftUI Image to show the image:

Image(xxx)
    .brightness(-0.5)

Then I used CIImage to generate a new image with this brightness adjustment:

func drawPic(img: UIImage) -> UIImage {
    let cgimage: CGImage = img.cgImage!
    let image = CIImage(cgImage: cgimage)
    let parameters = [
        "inputBrightness": Float(-0.5)
    ]
    let outputImage = image.applyingFilter("CIColorControls", parameters: parameters)
    let contextv = CIContext(options: nil)
    let CgPic = contextv.createCGImage(outputImage, from: outputImage.extent)!
    return UIImage(cgImage: CgPic)
}

But when I preview these images, I found that the colors of them is not the same:

Screenshot

Who can tell me why and how to solve this problem?

All Codes:

import SwiftUI
import UIKit
import CoreImage
import CoreImage.CIFilterBuiltins

struct TestImage: View {
    var body: some View {
        VStack{
            Image("colorcircle2").resizable().frame(width: 200, height: 200, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
            Text("Original Image").padding(.bottom, 24.0)
            Image("colorcircle2").resizable().frame(width: 200, height: 200, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).brightness(-0.5)
            Text("SwiftUI Image").padding(.bottom, 24.0)
            Image(uiImage: drawPic(img: UIImage(imageLiteralResourceName: "colorcircle2"))).resizable().frame(width: 200, height: 200, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
            Text("CIImage").padding(.bottom, 24.0)
        }
    }
}

func drawPic(img: UIImage) -> UIImage {
    let cgimage: CGImage = img.cgImage!
    let image = CIImage(cgImage: cgimage)
    let parameters = [
        "inputBrightness": Float(-0.5)
    ]
    let outputImage = image.applyingFilter("CIColorControls", parameters: parameters)
    let contextv = CIContext(options: nil)
    let CgPic = contextv.createCGImage(outputImage, from: outputImage.extent)!
    return UIImage(cgImage: CgPic)
}


struct TestImage_Previews: PreviewProvider {
    static var previews: some View {
        TestImage()
    }
}
0 Answers
Related