Android Glide:如何下载特定大小的位图?

Android Glide: How to download bitmap at specific size?

我正在使用 Glide 在 Scale ImageView 上加载图像 - 这是一个带有平移和缩放手势的自定义视图。我应该将 Bitmap 对象传递给此自定义视图以设置图片。

所以我可以使用 Glide 的 .asBitmap()SimpleTarget:

private SimpleTarget target = new SimpleTarget<Bitmap>() {  
    @Override
    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
       scaleImageView.setImage(ImageSource.bitmap(bitmap));
    }
};

private void loadImageSimpleTarget() {  
    Glide
        .with(context) 
        .load(url)
        .asBitmap()
        .into(target);
}

此代码片段运行良好,但我将获得全尺寸位图,这可能导致 OutOfMemoryErrors。我也可以像这样在构造函数上指定所需的位图大小:...new SimpleTarget<Bitmap>(250, 250)...,但我必须手动计算尺寸。

是否有可能将视图(CustomView 的实例)传递给 Glide 的请求,以便自动计算尺寸并接收 Bitmap 对象作为结果?

继续评论中的讨论,从 onCreateView 调用它时,宽度和高度为 0。但是,您可以设置一个侦听器,以便在实际计算视图边界时收到通知,然后您可以通过调用 getWidthgetHeight:

来获取实际的宽度和高度
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // ...
    // your other stuff
    // ...

    // set listener
    customView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Log.d("debug", "width after = " + customView.getHeight());

            // pass the width and height now that it is available
            target = new SimpleTarget<Bitmap>(customView.getWidth(), customView.getHeight()) {  
                @Override
                public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
                   scaleImageView.setImage(ImageSource.bitmap(bitmap));
                }
            };

            // remove listener, we don't need to be notified again.
            customView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
}