Android 如何在视图中覆盖画布?

Android 如何在视图中覆盖画布?,android,canvas,drawing2d,Android,Canvas,Drawing2d,我正在使用Android 2.1和Eclipse 我定义了一个线性布局,其中包含两个尺寸为250 x 250的组件 LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams llp = new llp.LayoutParams(250, 250); meter1View = new MeterView(this, "Meter

我正在使用Android 2.1和Eclipse

我定义了一个线性布局,其中包含两个尺寸为250 x 250的组件

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams llp = 
  new llp.LayoutParams(250, 250);

meter1View = new MeterView(this, "Meter 1");
ll.addView(meter1View, llp);
meter2View = new MeterView(this, "Meter 2");
ll.addView(meter2View, llp);   
ScrollView scrollView = new ScrollView(this);
scrollView.addView(ll);
setContentView(scrollView);
到目前为止,一切顺利。我在模拟器屏幕上看到两个垂直组件

但是,在我的Meter View类中,onDraw中画布的大小是模拟器屏幕的大小,即480 x 800

@Override
protected void onDraw(Canvas canvas) {
    int w = canvas.getWidth();
    int h = canvas.getHeight();
    Log.i(TAG, "  onDraw, w: " + w + ", h: " + h);
}
我希望画布的大小为250 x 250,这样我就可以将此画布传递给绘图例程。现在,我的绘图例程在LinearLayout定义的250 x 250位图之外绘图

我意识到,通过翻译画布,我可以使我的画布绘制例程正常工作,但如果我可以临时用新画布覆盖原始画布,它会更干净

我知道我可以通过以下方式定义自己的画布:

Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
如何用新画布替换视图类创建的画布? 任何帮助都将不胜感激


Charles

您应该使用视图的宽度和高度,而不是画布,这两个选项都可以通过getWidth()和getHeight()获得。然后将这些尺寸传递给绘图例程。

不要替换画布,只需使用clip rect即可