Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

前端 未结 17 1117
无人共我
无人共我 2020-11-22 17:07

How to fit an image of random size to an ImageView?
When:

  • Initially ImageView dimensions are 250dp * 250dp
  • The image\'
17条回答
  •  天命终不由人
    2020-11-22 17:40

    Use Simple math to resize the image . either you can resize ImageView or you can resize drawable image than set on ImageView . find the width and height of your bitmap which you want to set on ImageView and call the desired method. suppose your width 500 is greater than height than call method

    //250 is the width you want after resize bitmap
    Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
    ImageView image = (ImageView) findViewById(R.id.picture);
    image.setImageBitmap(bmp);
    

    You use this class for resize bitmap.

    public class BitmapScaler{
    // Scale and maintain aspect ratio given a desired width
    // BitmapScaler.scaleToFitWidth(bitmap, 100);
     public static Bitmap scaleToFitWidth(Bitmap b, int width)
      {
        float factor = width / (float) b.getWidth();
        return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
      }
    
    
      // Scale and maintain aspect ratio given a desired height
      // BitmapScaler.scaleToFitHeight(bitmap, 100);
      public static Bitmap scaleToFitHeight(Bitmap b, int height)
      {
        float factor = height / (float) b.getHeight();
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
       }
     }
    

    xml code is

    
    

提交回复
热议问题