android - how to get the image edge x/y position inside imageview

Here is a method I wanted to share, it will return the offset of the bitmap inside an imageView using getImageMatrix

public static int[] getBitmapOffset(ImageView img,  Boolean includeLayout) {
        int[] offset = new int[2];
        float[] values = new float[9];

        Matrix m = img.getImageMatrix();
        m.getValues(values);

        offset[0] = (int) values[Matrix.MTRANS_Y];
        offset[1] = (int) values[Matrix.MTRANS_X];

        if (includeLayout) {
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) img.getLayoutParams();
            int paddingTop = (int) (img.getPaddingTop() );
            int paddingLeft = (int) (img.getPaddingLeft() );

            offset[0] += paddingTop + lp.topMargin;
            offset[1] += paddingLeft + lp.leftMargin;
        }
        return offset;
    }

If you know the ratios you can just derive the width of the margin that will be placed to the side of the image.

// These holds the ratios for the ImageView and the bitmap
double bitmapRatio  = ((double)bitmap.getWidth())/bitmap.getHeight()
double imageViewRatio  = ((double)imageView.getWidth())/imageView.getHeight()

Now, if the bitmapRatio is larger than the imageViewRatio, you know that this means that the bitmap is wider than the imageview if they have an equal height. In other words, you'll have blanks on the top & bottom.

Conversely, if bitmapRatio is smaller than imageViewRatio then you'll have blanks to the left and right. From this you can get one of the co-ordinates pretty trivially as it'll be 0!

if(bitmapRatio > imageViewRatio)
{
  drawLeft = 0;
}
else
{
  drawTop = 0;
}

To get the other co-ordinate, think about the second case where you have space left & right. Here the heights of the the bitmap and imageView are equal and thus the ratio between the widths is equal to ratio between the ratios. You can use this to figure out width of the bitmap as you know the width of the imageView. Similarly you can figure out the heights if the width are equal, except that you have to use the inverse of the ratio between the ratios as the width is inversely proportional the the ratio:

if(bitmapRatio > imageViewRatio)
{
  drawLeft = 0;
  drawHeight = (imageViewRatio/bitmapRatio) * imageView.getHeight();
}
else
{
  drawTop = 0;
  drawWidth = (bitmapRatio/imageViewRatio) * imageView.getWidth();
}

Once you have the width or height of the bitmap, getting the space to the side is simple, it is just half the difference between the bitmap and imageView width or height:

if(bitmapRatio > imageViewRatio)
{
  drawLeft = 0;
  drawHeight = (imageViewRatio/bitmapRatio) * imageView.getHeight();
  drawTop = (imageView.getHeight() - drawHeight)/2;
}
else
{
  drawTop = 0;
  drawWidth = (bitmapRatio/imageViewRatio) * imageView.getWidth();
  drawLeft = (imageView.getWidth() - drawWidth)/2;
}