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

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

    Edited Jarno Argillanders answer:

    How to fit Image with your Width and Height:

    1) Initialize ImageView and set Image:

    iv = (ImageView) findViewById(R.id.iv_image);
    iv.setImageBitmap(image);
    

    2) Now resize:

    scaleImage(iv);
    

    Edited scaleImage method: (you can replace EXPECTED bounding values)

    private void scaleImage(ImageView view) {
        Drawable drawing = view.getDrawable();
        if (drawing == null) {
            return;
        }
        Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();
    
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int xBounding = ((View) view.getParent()).getWidth();//EXPECTED WIDTH
        int yBounding = ((View) view.getParent()).getHeight();//EXPECTED HEIGHT
    
        float xScale = ((float) xBounding) / width;
        float yScale = ((float) yBounding) / height;
    
        Matrix matrix = new Matrix();
        matrix.postScale(xScale, yScale);
    
        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();
        BitmapDrawable result = new BitmapDrawable(context.getResources(), scaledBitmap);
    
        view.setImageDrawable(result);
    
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); 
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }
    

    And .xml:

    
    

提交回复
热议问题