Glide等比例缩放

1、获取屏幕宽度

 ViewTreeObserver vto = journalismTitleEditor.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                journalismTitleEditor.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                DisplayMetrics dm = new DisplayMetrics();
                wm.getDefaultDisplay().getMetrics(dm);
                int width = dm.widthPixels;         // 屏幕宽度(像素)
//                int height = dm.heightPixels;       // 屏幕高度(像素)
                screenWidth = width; // 获取屏幕宽度
                LogUtils.i("屏幕宽度=" + screenWidth);
                }
    });

2、更改控件宽高

 SimpleTarget target = new SimpleTarget() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) {
                    if (resource != null) {
                        int imageWidth = resource.getWidth();
                        int imageHeight = resource.getHeight();
                        LogUtils.i("图片宽=" + imageWidth + " 图片高=" + imageHeight);
                        int width = imageWidth;
                        int height = imageHeight;
                        if (imageWidth > screenWidth) {
                            width = screenWidth;//固定宽度
                            //宽度固定,然后根据原始宽高比得到此固定宽度需要的高度
                            height = width * imageHeight / imageWidth;
                        }

                        ViewGroup.LayoutParams para = imageView.getLayoutParams();
                        para.height = height;
                        para.width = width;
                        imageView.setImageBitmap(resource);
                        imageView.setLayoutParams(para);
                    }

                }
            };
            String url = item.getImagePath();
            if (!TextUtils.isEmpty(url)) {
                url = url.trim();
                if (url.startsWith("http")) {
                    url = url.replace("http", "https");
                }
            }


            Glide.with(mContext).asBitmap().load(url).into(target);
 

        
    

最终效果
Glide等比例缩放_第1张图片

你可能感兴趣的:(Android实例)