Making deep copy of UIImage

前端 未结 6 1767
梦谈多话
梦谈多话 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:20

    Here is a way to do it:

    UIImage *imageToCopy = <# Your image here #>;
    UIGraphicsBeginImageContext(imageToCopy.size);
    [imageToCopy drawInRect:CGRectMake(0, 0, imageToCopy.size.width, imageToCopy.size.height)];
    UIImage *copiedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
    UIGraphicsEndImageContext();   
    

    The reason I needed this is that I had an image variable initialized with imageWithContentsOfFile:, and I wanted to be able to delete the file from disk but keep the image variable. I was surprised to find that when the file is deleted the image variable goes crazy. It was displaying wacky random data even though it was initialized before the file was deleted. When I deep copy first it works fine.

提交回复
热议问题