How to get the rectangle of the Drawable of ImageView on Android?

11,714

Solution 1

    Rect rect = new Rect();
    ImageView iV = new ImageView();

    rect.left = iV.getLeft();
    rect.top = iV.getTop();
    rect.bottom = iV.getBottom();
    rect.right = iV.getRight();

Now you have your rectangle.

Solution 2

You can use getImageMatrix() See: Android how to get bounds of imageview with matrix

Rect bounds = imageView.getDrawable().getBounds(); 
RectF boundsF = new RectF(bounds); 
imageView.getImageMatrix().mapRect(boundsF); 
boundsF.round(bounds); 

Solution 3

I know its an old question but if someone still needs this.

as I understand you are trying to get the blocking rectangle like so: blocking rectangle

If you are trying to get the Rect after the ImageView is drawn in the layout then you can call the View.getHitRect(Rect) method which will give you the blocking Rect of the Drawable inside the image view.

val rect = Rect()
view.getHitRect(rect)
Share:
11,714
ipman
Author by

ipman

Updated on June 05, 2022

Comments

  • ipman
    ipman about 2 years

    I want to get the rectangle object that will wrap the Drawable of ImageView instead of the rectangle that will wrap the ImageView. I will use that rectangle to draw some fancy rectangle around Drawable. How can I get that rectangle?

  • ipman
    ipman over 12 years
    this gives the rectangle surrounding ImageView, but I want the rectangle surrounding the Drawable in ImageView.
  • ipman
    ipman over 12 years
    this only gives the width and height of the Drawable, but I want the rectangle that surrounds the Drawable.
  • Andreas
    Andreas over 12 years
    can you some better explain what you mean? Do you mean the layout out from the ImageView?
  • ipman
    ipman over 12 years
    No I mean, sometimes ImageView has some space beetween its bounds and Drawable in the ImageView. I do not want to include this spacing in my rectangle.
  • Andreas
    Andreas over 12 years
    A Imageview is only a View (extended) that draws a Bitmap, i think you cant get other sizes as from ImageView/Drawable/Bitmap as in known size functions. Only a ImageView can have a padding (its inside the view and can reduce the "imagesize" itself, so you can ask for padding in the ImageView and compare it with the rect(width/height) of the real drawable/bitmap.
  • android developer
    android developer about 9 years
    Did you understand the part of the 0.25f ? Why do you think it has to do with density, if all things here are in pixels ?