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

前端 未结 17 1096
无人共我
无人共我 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:49

    The Below code make the bitmap perfectly with same size of the imageview. Get the bitmap image height and width and then calculate the new height and width with the help of imageview's parameters. That give you required image with best aspect ratio.

    int currentBitmapWidth = bitMap.getWidth();
    int currentBitmapHeight = bitMap.getHeight();
    
    int ivWidth = imageView.getWidth();
    int ivHeight = imageView.getHeight();
    int newWidth = ivWidth;
    
    newHeight = (int) Math.floor((double) currentBitmapHeight *( (double) new_width / (double) currentBitmapWidth));
    
    Bitmap newbitMap = Bitmap.createScaledBitmap(bitMap, newWidth, newHeight, true);
    
    imageView.setImageBitmap(newbitMap)
    

    enjoy.

提交回复
热议问题