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

前端 未结 4 836
不知归路
不知归路 2020-12-23 15:01

If i have an ImageView that fills the screen.
The ImageView background is set to green color.
I place a bitmap in the ImageView, keeping bitmap proportions.

4条回答
  •  再見小時候
    2020-12-23 15:42

    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;
    }
    

提交回复
热议问题