ImageView fills parent's width OR height, but maintains aspect ratio

后端 未结 7 559
礼貌的吻别
礼貌的吻别 2020-12-04 18:07

I have a square image (though this problem also applies to rectangular images). I want to display the image as large as possible, stretching them if necessary, to fill thei

7条回答
  •  佛祖请我去吃肉
    2020-12-04 18:37

    Did you try to adjust it programmaticaly? I think it works really well if you calculate the height of your TextViews and adjust the height and width of the image based on this.

    private void adjustImageView()
    {
        //Get the display dimensions
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
        //TextView name
        TextView name = (TextView) findViewById(R.id.name);
        name.setText("your name text goes here");
        name.measure(0, 0);
    
        //name TextView height
        int nameH = name.getMeasuredHeight();
    
        //TextView name2
        TextView name2 = (TextView) findViewById(R.id.name2);
        name2.setText("your name2 text goes here");
        name2.measure(0, 0);
    
        //name2 TextView height
        int name2H = name2.getMeasuredHeight();
    
        //Original image
        Bitmap imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.image);
    
        //Width/Height ratio of your image
        float imageOriginalWidthHeightRatio = (float) imageOriginal.getWidth() / (float) imageOriginal.getHeight();
    
        //Calculate the new width and height of the image to display 
        int imageToShowHeight = metrics.heightPixels - nameH - name2H;
        int imageToShowWidth = (int) (imageOriginalWidthHeightRatio * imageToShowHeight);
    
        //Adjust the image width and height if bigger than screen
        if(imageToShowWidth > metrics.widthPixels)
        {
            imageToShowWidth = metrics.widthPixels;
            imageToShowHeight = (int) (imageToShowWidth / imageOriginalWidthHeightRatio);
        }
    
        //Create the new image to be shown using the new dimensions 
        Bitmap imageToShow = Bitmap.createScaledBitmap(imageOriginal, imageToShowWidth, imageToShowHeight, true);
    
        //Show the image in the ImageView
        ImageView image = (ImageView) findViewById(R.id.image);
        image.setImageBitmap(imageToShow);
    }
    

提交回复
热议问题