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

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

    I needed to get this done in a constraint layout with Picasso, so I munged together some of the above answers and came up with this solution (I already know the aspect ratio of the image I'm loading, so that helps):

    Called in my activity code somewhere after setContentView(...)

    protected void setBoxshotBackgroundImage() {
        ImageView backgroundImageView = (ImageView) findViewById(R.id.background_image_view);
    
        if(backgroundImageView != null) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int width = displayMetrics.widthPixels;
            int height = (int) Math.round(width * ImageLoader.BOXART_HEIGHT_ASPECT_RATIO);
    
            // we adjust the height of this element, as the width is already pinned to the parent in xml
            backgroundImageView.getLayoutParams().height = height;
    
            // implement your Picasso loading code here
        } else {
            // fallback if no element in layout...
        }
    }
    

    In my XML

    
    
    
    
        
    
        
    
    
    

    Note the lack of a constraintBottom_toBottomOf attribute. ImageLoader is my own static class for image loading util methods and constants.

提交回复
热议问题