DeliveryNinja
DeliveryNinja

Reputation: 827

Getting the bounds when drawing on the canvas in android

I am drawing a Drawable to a custom view in android.

When the custom view is displayed the parent is a ScrollView. When the scrollview moves the Drawables shrink until they get off screen and then get bigger as you scroll back to the custom widget even though its explicitly set at 219dip square.

The reason seems to be the way I'm getting the bounds in the onDraw(Canvas canvas) method

    int mRight;
    int mLeft;
    int mBottom;
    int mTop;

    mRight = canvas.getClipBounds().right; 
    mLeft = canvas.getClipBounds().left;
    mBottom = canvas.getClipBounds().bottom;
    mTop = canvas.getClipBounds().top;

    int availableWidth = mRight - mLeft;
    int availableHeight = mBottom - mTop;

It seems that the ClipBound changes to reflect how much of the view is on the screen. Therefore resize the Drawables until it gets really small and goes off screen.

I tried to replace the code above with this

    int availableWidth = canvas.getWidth();
    int availableHeight = canvas.getHeight();

Nothing is drawn to the screen now? shouldn't this work?

Upvotes: 1

Views: 8804

Answers (2)

DeliveryNinja
DeliveryNinja

Reputation: 827

This works for my custom View, this code goes in the onDraw(Canvas canvas) method.

    mRight = this.getRight();
    mLeft = this.getLeft();
    mBottom = this.getBottom();
    mTop = this.getTop();

    int availableWidth = mRight - mLeft;
    int availableHeight = mBottom - mTop;

previous answer was wrong, view has no method getBounds()

Upvotes: 4

Brian ONeil
Brian ONeil

Reputation: 4339

When drawing my custom Drawable I use:

float w = this.getBounds().width();
float h = this.getBounds().height();

to get the bounding area of the my Drawable in the draw(Canvas canvas)method. I have not tried this in a ScrollView, but I would think that the bounds of the Drawable should work the same either way.

Hope this helps.

Upvotes: 4

Related Questions