简体   繁体   English

如何用图像替换UIView?

[英]How do I replace a UIView with an image?

In my program, I did something like this video and made my UIView draggable. 在我的程序中,我做了类似视频的操作,并使UIView可拖动。 I am making a Space Invaders type game where I would need that UIView to be the spaceship. 我正在制作“太空侵略者”类型的游戏,在该游戏中,我需要UIView才能成为飞船。 It is currently just a normal UIView white rectangle. 当前它只是一个普通的UIView白色矩形。 Is there a way to replace that white rectangle that is the UIView to an image? 有没有办法将UIView的白色矩形替换为图像? Or am I going at solving this the wrong way? 还是我要以错误的方式解决这个问题?

Is there a way to replace that white rectangle that is the UIView to an image? 有没有办法将UIView的白色矩形替换为图像?

Sure, you can use a UIImageView in place of the UIView that you're currently using. 当然,您可以使用UIImageView代替当前使用的UIView Then you just configure the image view to display whatever image you want. 然后,您只需配置图像视图即可显示所需的任何图像。

Another option is to create your own subclass of UIView that knows how to draw its content (a spaceship in this case). 另一个选择是创建自己的UIView子类,该子类知道如何绘制其内容(在这种情况下为太空船)。

Or am I going at solving this the wrong way? 还是我要以错误的方式解决这个问题?

Games like the one you're building often draw the parts of the game using sprites, which are animatable sequences of 2D images. 诸如您正在构建的游戏之类的游戏通常使用Sprite绘制游戏的各个部分,Sprite是2D图像的可动画序列。 This is such a common thing that many platforms provide libraries that are dedicated to drawing and moving sprites efficiently. 这是很常见的事情,许多平台都提供了专门用于有效绘制和移动精灵的库。 On iOS, that library is called SpriteKit , and it's probably a better choice for what you're trying to do than trying to draw everything with views. 在iOS上,该库称为SpriteKit ,与尝试使用视图绘制所有内容相比,它可能是您尝试做的更好的选择。

Likewise, there's a framework called SceneKit for working with 3D objects. 同样,有一个名为SceneKit的框架用于处理3D对象。 That's probably more advanced than what you want, especially if you're just getting started. 这可能比您想要的要先进,尤其是在您刚刚入门时。

you don't need to replace it, you can add a UIImageView to the UIView 您不需要替换它,可以将UIImageView添加到UIView

UIView *view = your view;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:view.frame];
[imageView setImage:[UIImage imageNamed:@""]];
[view addSubview:imageView];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM