How to scale an Image in ImageView to keep the aspect ratio

前端 未结 25 2339
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:59

In Android, I defined an ImageView\'s layout_width to be fill_parent (which takes up the full width of the phone).

If the imag

25条回答
  •  自闭症患者
    2020-11-22 05:08

    Pass your ImageView and based on screen height and width you can make it

        public void setScaleImage(EventAssetValueListenerView view){
            // Get the ImageView and its bitmap
            Drawable drawing = view.getDrawable();
            Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
            // Get current dimensions
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
    
            float xScale = ((float) 4) / width;
            float yScale = ((float) 4) / height;
            float scale = (xScale <= yScale) ? xScale : yScale;
    
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);
    
            Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            BitmapDrawable result = new BitmapDrawable(scaledBitmap);
            width = scaledBitmap.getWidth();
            height = scaledBitmap.getHeight();
    
            view.setImageDrawable(result);
    
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
            params.width = width;
            params.height = height;
            view.setLayoutParams(params);
        }
    

提交回复
热议问题