Android 新手 - 在运行时绘制视图
大家好,
我刚刚开始进行 Android 开发。我正在寻找移植我的 iPhone 应用程序之一,但我有点不知道如何在运行时绘制视图(未在 XML 中声明的视图)。基本上,我想绘制一个简单的矩形,但在绘制后能够操纵它的框架。
抱歉,如果这是一个非常非常简单的问题,但我似乎无法在这里找到与 iPhone SDK 等效的东西。
提前致谢!
HI all,
I'm just getting started with developing for Android. I'm looking to port one of my iPhone applications, but I'm kind of at a loss for how to draw a view at runtime (a view not declared in the XML). Basically, I want to draw a simple rectangle, but then be able to manipulate its frame after being drawn.
Sorry if this is a really, really simple question, but I can't seem to find some equivalent to the iPhone SDK here.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想尝试 2D 图形 - 为此,您应该使用
Canvas
。您可以通过invalidate()
方法控制 Canvas 的绘制,该方法告诉 Android 重新绘制整个内容,从而触发您自定义的onDraw()
方法。您提到不想使用 XML 文件,但这是放入 Canvas 的最简单方法 - 您不必在 XML 文件中定义其内容,而只需告诉布局文件它在那里。将 Canvas 放入应用程序中的一种强大但简单的方法是自定义视图。例如,在 XML 文件中包含
元素。然后声明CustomView extends View
类。您想要进行的任何类型的绘图都可以放入 onDraw() 方法中。例如,要绘制一个矩形,请执行以下操作。
每次从程序中调用 invalidate() 时,都会重新绘制视图,并且矩形将向下和向右移动 2px。注意:重绘仅在主线程“等待”时发生。换句话说,如果循环多次调用 invalidate,则在循环完成之前不会真正绘制视图。您可以解决这个问题,但这会增加更多的复杂性。有关如何完成此操作的示例,请查看 Google 的 LunarLander 示例游戏 - 这是一个简单的游戏,演示了自定义视图、2 个线程以及如何实现连续动画。
It sounds like you want to experiment with 2D graphics - for that, you should use a
Canvas
. You can control the drawing of the Canvas through theinvalidate()
method, which tells Android to redraw the whole thing triggering your customisedonDraw()
method. You mention not wanting to use the XML file, but that is the simplest way to put in a Canvas - you don't have to define its contents in the XML file, but simply tell the layout file it's there. A powerful but simple way to put a Canvas in your application is to customise a View. For example, include in your XML file a<your.package.CustomView android:.../>
element. Then declare theCustomView extends View
class. Any kind of drawing you want to do, put in the onDraw() method.For example, to draw a rectangle, do something like this.
Every time invalidate() is called from your program, the view will be redrawn and the rectangle moved 2px down and to the right. Note: the redrawing only happens with the main thread is 'waiting'. In other words, if you have a loop calling invalidate several times, the View won't actually be drawn until the loop finishes. You can get around this, but that adds more complication. For an example of how that's done, look at the LunarLander example game from Google - it's a simple game demonstrating a custom View, 2 threads, and how to implement continuous animation.