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 can开发者_JS百科vas) 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?
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.
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()
精彩评论