如何克隆UIImageView

时间:2014-08-22 03:47:41

标签: ios xcode uiimageview

我有一个UIImageView,我想复制它并将它放在屏幕上的某个地方。我该怎么做?

我目前只知道如何手动复制和粘贴图像,并为每个图像创建一个单独的IBOutlet,但这是非常低效的,因为我想制作一个永远产生障碍(UIImageViews)的游戏,所以我不能这样做手动方式。

2 个答案:

答案 0 :(得分:2)

您需要创建一个新的UIImageView,并在其中放置新框架。设置现有imageView图像的图像属性,然后将其添加到视图中。

UIImageView *newImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,50,50)];
newImageView.image = oldImageView.image;
[self.view addSubView:newImageView]

答案 1 :(得分:2)

您希望确保匹配所有属性,例如尺寸,剪裁,图像宽高比,不透明度等。

CGPoint locationOfCloneImageView = CGPointMake(0, 0);//x and y coordinates of where you want your image. (More specifically, the x and y coordinated of where you want the CENTER of your image to be)

UIImageView *cloneImageView = [[UIImageView alloc] initWithImage:originalImageView.image];
cloneImageView.frame = CGRectMake(0, 0, originalImageView.frame.size.width, originalImageView.frame.size.height);//same size as old image view
cloneImageView.alpha = originalImageView.alpha;//same view opacity
cloneImageView.layer.opacity = originalImageView.layer.opacity;//same layer opacity
cloneImageView.clipsToBounds = originalImageView.clipsToBounds;//same clipping settings
cloneImageView.backgroundColor = originalImageView.backgroundColor;//same BG color
cloneImageView.tintColor = originalImageView.tintColor;//matches tint color.
cloneImageView.contentMode = originalImageView.contentMode;//matches up things like aspectFill and stuff.
cloneImageView.highlighted = originalImageView.highlighted;//matches whether it's highlighted or not
cloneImageView.opaque = originalImageView.opaque;//matches can-be-opaque BOOL
cloneImageView.userInteractionEnabled = originalImageView.userInteractionEnabled;//touches are detected or not
cloneImageView.multipleTouchEnabled = originalImageView.multipleTouchEnabled;//multi-touches are detected or not
cloneImageView.autoresizesSubviews = originalImageView.autoresizesSubviews;//matches whether or not subviews resize upon bounds change of image view.
//cloneImageView.hidden = originalImageView.hidden;//commented out because you probably never need this one haha... But if the first one is hidden, so is this clone (if uncommented)
cloneImageView.layer.zPosition = originalImageView.layer.zPosition+1;//places it above other views in the parent view and above the original image. You can also just use `insertSubview: aboveSubview:` in code below to achieve this.
[originalImageView.superview addSubview:cloneImageView];//adds this image view to the same parent view that the other image view is in.

cloneImageView.center = locationOfCloneImageView;//set at start of code.