How can I draw a Rectangle in Android, of a given size, that positions itself in the view to which it is added?

electricSunny picture electricSunny · Dec 5, 2011 · Viewed 20.3k times · Source

I understand how to draw I shape, I am extending the View class, and overriding the onDraw, where I create a new ShapeDrawbale (Rectangle), which I then draw to the canvas:

    Rect rect = new Rect(x, y, x + width, y + height);
    shapeDrawable.setBounds(rect);
    shapeDrawable.getPaint().set(paint);
    shapeDrawable.draw(canvas);

I then want to add this to a view defined in my Activities layout xml. I do this by getting a handle on the view and calling:

innerLinear.addView(rectView); // where rectView is my custom class that extends View

My problem is that when creating the Rectangle, you have to provide X and Y coordinates.

So - how do I get the rectanlge positioned correctly within the innerLayout?

Do I have use the bounds of innerLayout to create the rectangle? If so, when I call innerLayout.getLeft(), or innerLayout.getTop() etc.. 0 is always returned (I presume layout has not yet fully completed), so how do I do this?

Is there another way? I feel like I'm missing something pretty basic here.

Any help would be greatly appreciated,

thanks

Answer

havexz picture havexz · Dec 5, 2011

In the onDraw method you can use following apis:

For x and y, the reference point is 0,0 with respect to parent view.

getWidth() // This is in View
getHeight() // This is in View

When you call above apis in your CustomView you will get the right dimensions of the parent view which in your case is innerLayout. Now if I have to cover all the area I ll write something like:

Rect rect = new Rect(0, 0, getWidth(), getHeight());

This will fill your CustomView completely. How your 0, 0 is mapped to the actual screen coordinates, you dont worry about it. As I mentioned, your view's reference point is 0,0. And Android will calculate the actual screen coordinates.

For further ref:

Custom Components

How Android draws