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

后端 未结 7 533
礼貌的吻别
礼貌的吻别 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

    Set android:layout_height="wrap_content" in imageview. To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following. Here I mention how to load image to imageview from url.

    Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
    
                            // creating the image that maintain aspect ratio with width of image is set to screenwidth.
                            int width = imageView.getMeasuredWidth();
                            int diw = resource.getWidth();
                            if (diw > 0) {
                                int height = 0;
                                height = width * resource.getHeight() / diw;
                                resource = Bitmap.createScaledBitmap(resource, width, height, false);
                            }
                                                  imageView.setImageBitmap(resource);
                        }
                    });
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题