制作UIImage的深层副本 [英] Making deep copy of UIImage

查看:102
本文介绍了制作UIImage的深层副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类包含一个UIImage属性,我希望任何访问它的外部客户端都可以将其强制为复制属性。但是,当我尝试在我的自定义setter中复制时,我得到关于UIImage不支持copyWithZone的运行时错误。那么确保遵循正确的所有权政策的好方法是什么?

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, I get the runtime error about UIImage not supporting copyWithZone. So what's a good way to ensure that the correct ownership policy is followed?

// declared in the interface as:
@property (nonatomic, readonly, copy) UIImage *personImage;

// class implementation
- (void)setPersonImage:(UIImage *)newImage
{
    if (newImage != personImage) 
    {
        [personImage release];

        // UIImage doesn't support copyWithZone
        personImage = [newImage copy];
    }
}


推荐答案

这里是一种方法:

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

我需要这个的原因是我有一个用imageWithContentsOfFile初始化的图像变量:我想要能够从磁盘中删除文件但保留图像变量。我很惊讶地发现,当文件被删除时,图像变量变得疯狂。它显示了古怪的随机数据,即使它在删除文件之前已经初始化。当我首先进行深度复制时,它可以正常工作。

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.

这篇关于制作UIImage的深层副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆