How do you create a copy of an UIImageView instance?

佐手、 提交于 2020-01-01 08:19:12

问题


How do I create a copy of an UIImageView instance that can be manipulated independently of the first instance?

I've tried UIImageView *tempCopy = [instance copy] but it crashes. Is there another way?


回答1:


It probably crashes because UIImageView doesn't conform to the NSCopying protocol. So do it yourself: instantiate a new UIImageView and set any property from your original that you find of interest.




回答2:


UIImageView doesn't conform to NSCopying, but it does conform to NSCoding. Archive your view, and then de-archive it to get a brand new copy.

For the lazily inclined, this looks like:

NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:imageView];
UIImageView *copy = [NSKeyedUnarchiver unarchiveObjectWithData:data];



回答3:


In answer to the response of Mike Abdullah... the question is that he needs to save all the subviews already existing in his image view...

the problem of using that approach is that the default implementation of NSCoding won't save those views... so he would have to override the method and provide deep coding (for those efforts he better conforms to NSCopying and perform the deep copy)

If all you need is a static image (the subviews don't provide interaction) i would recommend doing the following

UIGraphicsBeginImageContext(imageView.rect.size);

[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *copyImageView = [[UIImageView alloc] initWithImage:viewImage];

This will ensure that tue subviews get all saved as a static image...

if you need a copy that has the subviews that retain their interaction... this would not help you...

Greetings



来源:https://stackoverflow.com/questions/4621922/how-do-you-create-a-copy-of-an-uiimageview-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!