如何在Android中为自定义视图调用onDraw方法? [英] How do I call onDraw method for custom view in Android?

查看:496
本文介绍了如何在Android中为自定义视图调用onDraw方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款Android游戏,我需要在自定义视图上绘制一个二维圆阵列。我有绘制圆圈的方法,但不知道如何调用它。以下是它的代码。

I am working on an Android game where I need to draw a 2d array of circles onto a custom view. I have the method to draw the circles, but don't know how to call it. Here is the code for it.

public Canvas drawCircles(Canvas canvas) {
		circlePaint = new Paint();
		circlePaint.setDither(true);
		circlePaint.setColor(Color.BLACK);  // alpha.r.g.b
		circlePaint.setStyle(Paint.Style.STROKE);
		circlePaint.setStrokeJoin(Paint.Join.ROUND);
		circlePaint.setStrokeCap(Paint.Cap.ROUND);
		circlePaint.setStrokeWidth(2);

		int numCircles = screenWi / 100;
		int circleDia = screenWi / numCircles;
		for (int i = 0; i < numCircles; i++) {
			for (int j = 0; i < numCircles; j++) {
				circleLocations.add(new Point(screenWi - (j * (circleDia / 2)), screenHi - (i * (circleDia / 2))));
			}
		}

		for (Point point : circleLocations) {
			canvas.drawCircle(point.x, point.y, circleDia / 2, circlePaint);
		}
		return canvas;
	}

我对如何做到这一点几乎一无所知。另外,如何获得screenWi和screenHi。我有一个onMeasure方法,只是调用它的超级。谢谢!!

I am pretty much clueless on how to do this. Also, how to do you get the screenWi and screenHi. I have an onMeasure method that just calls its super. Thanks!!

推荐答案

在onDraw函数中调用此方法:

Call this method in the onDraw function:
protected void onDraw (Canvas canvas) {
          drawCircles(canvas);
}



每次刷新UI时,都会调用onDraw函数。触发UI刷新。只是使您的自定义视图无效。例如


Every time when your UI is refreshed, the onDraw function will be called. To trigger the UI refresh. Just invalidate your custom view. For example

mCustomerView.invalidate();


这篇关于如何在Android中为自定义视图调用onDraw方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆