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

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

    I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).

    I was looking through this post for how to do it, and finally did what I want, not the way described here though.

    
    
    
    

    and then in onCreateView method

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
        View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);
    
        progress = view.findViewById(R.id.progress);
    
        imageView = view.findViewById(R.id.acpt_image);
        imageView.setImageBitmap( bitmap );
    
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
            layoutImageView()
        );
    
        return view;
    }
    

    and then layoutImageView() code

    private void layoutImageView(){
    
        float[] matrixv = new float[ 9 ];
    
        imageView.getImageMatrix().getValues(matrixv);
    
        int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
        int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );
    
        imageView.setMaxHeight(h);
        imageView.setMaxWidth(w);
    
    }
    

    And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.

    Result

    It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,

    /*An optional argument to supply a maximum height for this view. Only valid if
     * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
     * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
     * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
     * layout params to WRAP_CONTENT. */
    

提交回复
热议问题