简体   繁体   中英

SWIFT 3 - CGImage copy always nil

having this problem and trying to fix it for hours.

func changeColorByTransparent(colorMasking : [CGFloat]) {

    UIGraphicsBeginImageContext(self.symbolImageView.frame.size)
    self.symbolImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    self.symbolImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    if let image = self.symbolImageView.image {
        print("image ok")
        if let cgimage = image.cgImage {
            print("cgimage ok")
            if let imageRef = cgimage.copy(maskingColorComponents: colorMasking) {
                print("imageRef ok")
                self.symbolImageView.image = UIImage(cgImage: imageRef, scale: (self.symbolImageView.image?.scale)!, orientation: (self.symbolImageView.image?.imageOrientation)!)
            }
        }
    }
}

The console give me :

image ok
cgimage ok

It always tell me that imageRef is nil but the debug find an image for symbolImageView.image and this image is in JPG. The colorMasking is like colorMasking = [222,255,222,255,222,255] so no problem neither.

Thank you very much for your time.

The source for copy(maskingColorComponents components: [CGFloat]) cannot have an alpha component. The way you are getting an image with UIGraphicsGetImageFromCurrentImageContext results in an alpha component.

Try this:

func changeColorByTransparent(imgView: UIImageView, cMask: [CGFloat]) -> UIImage? {

    var returnImage: UIImage?

    if let capImage = imgView.image {

        let sz = capImage.size

        UIGraphicsBeginImageContextWithOptions(sz, true, 0.0)
        capImage.draw(in: CGRect(origin: CGPoint.zero, size: sz))
        let noAlphaImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        let noAlphaCGRef = noAlphaImage?.cgImage

        if let imgRefCopy = noAlphaCGRef?.copy(maskingColorComponents: cMask) {

            returnImage = UIImage(cgImage: imgRefCopy)

        }

    }

    return returnImage

}

and call it like this:

var cMask : [CGFloat] = []

cMask = [222, 255, 222, 255, 222, 255]

let newImage = changeColorByTransparent(imgView: symbolImageView, cMask: cMask)

(assuming you have a UIImageVIew named "symbolImageView")

and, to get around an odd alpha channel issue when saving the resulting image:

func saveImageWithAlpha(theImage: UIImage, destFile: URL) -> Void {

    // odd but works... solution to image not saving with proper alpha channel
    UIGraphicsBeginImageContext(theImage.size)
    theImage.draw(at: CGPoint.zero)
    let saveImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    if let img = saveImage, let data = UIImagePNGRepresentation(img) {

        try? data.write(to: destFile)

    }

}

I'd have look into this one a little more to figure out what's actually wrong.

Let's start with this: break your if-let into a nested if-let. Just for the sake of figuring out which value is returning nil.

if let image = self.symbolImageView.image? {
   if let cgImage = image.cgImage {
      ...
   }
}

Set some break points, step through and let me know what you find.

______________________________EDIT ONE______________________________

So taking a quick look at the docs for copy(maskingColorComponents:) it seems like there could be a problem with the components array.

Components:

An array of color components that specify a color or range of colors to mask the image with. The array must contain 2N values { min 1 , max 1 , ... min[N], max[N] } where N is the number of components in color space of image. Each value in components must be a valid image sample value. If image has integer pixel components, then each value must be in the range [0 .. 2**bitsPerComponent - 1] (where bitsPerComponent is the number of bits/component of image). If image has floating-point pixel components, then each value may be any floating-point number which is a valid color component.

Are you certain that your values are valid for your image?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM