Making deep copy of UIImage

前端 未结 6 1770
梦谈多话
梦谈多话 2020-12-16 15:44

My class contains an UIImage property which I want to enforce as a \'copy\' property by any external clients accessing it. But, when I try to do a copy in my custom setter,

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 16:02

    A deep copy

    When talking about deep copies we must first understand that UIImage is a container. It doesn't actually contain the image data. The underlying data can be a CIImage or a CGImage. In most cases the backing data is a CGImage which is in turn a wrapping struct and copying the CGImage is just copying the metadata and not the underlying data. If you want to copy the underlying data you can draw the image into a context or grab a copy of the data as a PNG.

    UIImagePNGRepresentation

    Creating a playground with the following demonstrates the method.

    let zebra = UIImage(named: "an_image_of_a_zebra")
    print(zebra?.CGImage) // check the address
    let shallowZebra = UIImage(CGImage: zebra!.CGImage!) 
    print(shallowZebra.CGImage!) // same address
    
    let zebraData = UIImagePNGRepresentation(zebra!)
    let newZebra = UIImage(data: zebraData!)
    print(newZebra?.CGImage) // new address
    

提交回复
热议问题