New to Android - Drawing a view at runtime

妖精的绣舞 提交于 2019-11-30 20:26:40
Steve Haley

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 the invalidate() method, which tells Android to redraw the whole thing triggering your customised onDraw() 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 the CustomView 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.

//First you define a colour for the outline of your rectangle
rectanglePaint = new Paint();
rectanglePaint.setARGB(255, 255, 0, 0);
rectanglePaint.setStrokeWidth(2);
rectanglePaint.setStyle(Style.STROKE);

//Then create yourself a Rectangle
Rect rectangle = new Rect(left, top, right, bottom) //in pixels

//And here's a sample onDraw()
@Override
public void onDraw(Canvas canvas){
    rectangle.offset(2, 2);
    canvas.drawRect(rectangle, rectanglePaint);
}

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.

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