Search code examples
androidimageviewscale

Android Scale Image to largest size


Hi i'm working on an application that will be loading images and i'm looking to scale each image to it's largest possible size for instance if the image is a landscape image (if width is larger than height) i would like to stretch the width to fill the width of the phone and scale height to keep it's aspect ratio. If the height is larger than the width i.e. a portrait image the image should be scaled to fit the height of the phone and width should then adjust to keep the aspect ratio i've had a bit of trouble getting this to work here's what i've done so far though any help would be greatly appreciated.

            final ImageView i = new ImageView(mContext);
            i.setImageResource(mImageIds[position]);
            i.setBackgroundResource(android.R.color.black);
            //TODO need to get actual size of drawable not view size which is 0
            ViewTreeObserver vto = i.getViewTreeObserver();
            vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                public boolean onPreDraw() {
                    int w = i.getMeasuredWidth();
                    int h = i.getMeasuredHeight();
                    Display display = getWindowManager().getDefaultDisplay(); 
                    int width = display.getWidth();
                    int height = display.getHeight();
                    if(w <= h){
                        //TODO need to think about landscape
                        h = height - convertDpToPixel(50, context);
                        w = w*(width);
                    }else{
                        h = h*(height);
                        w = width;
                    }
                    //TODO set imageview to w and h

                    return true;
                }
            });

Solution

  • for get Display width , height

    DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int wwidth = displaymetrics.widthPixels;
    

    For Resize Imageview

    ImageView img=(ImageView)findViewById(R.id.ImageView01);
    Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.sc01);
    Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true);
    img.setImageBitmap(resizedbitmap);