Scaling ImageView to device width

前端 未结 9 849
清酒与你
清酒与你 2020-12-05 00:54

In my Android App I have a Activity which show images which have following size 244 x 330. I want to show those images in full device width.

My layout f

9条回答
  •  有刺的猬
    2020-12-05 01:46

    Slightly confused on what you're looking for, exactly. If you're scaling to fit the screen, you have three options, two of which are viable if you're keeping proportions. You can use ScaleType fitCenter, which will make the image fit within the bounds proportionally, or you can use centerCrop (which you said you tried), which will stretch the shortest side of the image to fit the container (meaning some will get cropped off on the longer dimension). You can't have it stretch to fit the width AND height without either cropping, or stretching disproportionately.

    EDIT: Okay, I think I get your point now. First, I'd set your LinearLayout to wrap_content for the height. Second, in code, here's one way you can do it that I can think of. There's probably also another way you could do it by first getting the screen dimensions, and then doing createScaledBitmap with the new dimensions, and then setting the background resource.

    final ImageView newsImage = (ImageView)findViewById(R.id.news_image);
    
    //get details on resolution from the display
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
    //going to set what happens as the layout happens
    newsImage.getViewTreeObserver().addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
    
            public void onGlobalLayout() {
                int oldHeight, oldWidth, newHeight, newWidth;
    
                //we want the new width to be as wide as the screen
                newWidth = metrics.widthPixels;
    
                oldHeight = newsImage.getDrawable().getIntrinsicHeight();
                oldWidth = newsImage.getDrawable().getIntrinsicWidth();
    
                //keeping the aspect ratio, the new height should be w1/h1 = w2/h2
                newHeight = Math.floor((oldHeight * newWidth) / oldWidth);
                LinearLayout.LayoutParams params = 
                    (LinearLayout.LayoutParams)newsImage.getLayoutParams();
                params.height = newHeight;
                params.width = newWidth;
                newsImage.setLayoutParams(params);
                newsImage.setScaleType(ScaleType.CENTER);
                newsImage.invalidate();
                newsImage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        }
    }
    

提交回复
热议问题