views:

167

answers:

2

I am using Android 2.1 and Eclipse.

I have defined a LinearLayout with two components that have dimensions: 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);

So far, so good. I see two vertical compoments on my emulator screen.

However, in my Meter View class, the size of the canvas in onDraw is the size of my emulator screen, which is 480 by 800.

@Override
protected void onDraw(Canvas canvas) {
    int w = canvas.getWidth();
    int h = canvas.getHeight();
    Log.i(TAG, "  onDraw, w: " + w + ", h: " + h);
}

I would like a canvas size to be 250 x 250, so that I can pass this canvas to drawing routines. Right now, my drawing routines are drawing outside the 250 x 250 bitmap that was defined by my LinearLayout.

I realize that I can make my canvas drawing routine to work by translating the canvas, but it would be cleaner if I could temporarily override the original canvas with a new one.

I understand that I can define my own canvas by:

Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);

How can I replace the canvas that is created by the View class with my new canvas? Any help will be greatly appreciated.

Charles

A: 

you should use the width and height of the view, not the canvas, both available via getWidth() and getHeight(). Then pass these dimensions to your drawing routine.

Karl R
A: 

Don't replace the Canvas, just use the clip rect instead.

Romain Guy