Glide:加载可绘制但不缩放占位符

Glide: load drawable but don't scale placeholder

有没有一种方法可以使用 Glide 分配占位符,同时保持图像的原始比例? 我有一个 ImageView 大小可变(取决于传入的图像),我在调用 Glide.with().load().into() 之前设置了它,我想为其使用占位符但不希望将占位符调整为大小ImageView,我希望它保持原来的大小。

到目前为止,我找不到方法来做到这一点。

有一个known Glide issue of placeholders distorting loaded images and vice versa。但是我认为你不会受到影响。

听起来您想要的是用 scaleType="center" 显示可绘制的占位符,并且您希望加载的图像是 scaleType="fitCenter"。以下是您在 Glide 中的表达方式。在 XML 中添加 android:scaleType="center" 并使用以下 Glide 载入线:

Glide.with(...).load(...).placeholder(R.drawable....).fitCenter().into(imageView);

诀窍是占位符是通过 setImageDrawable() 设置的,所以 ImageView 将像往常一样显示它,但是你告诉 Glide 显式地使用 FitCenter 这将很好地适应加载的图像通过 Transformation 调整 ImageView 的布局大小,然后通过 setImageDrawable() 设置它。由于拟合图像非常适合,center 将只绘制覆盖整个视图区域的图像。

你也可以用同样的方法.centerCrop()

如果出现问题,您可以尝试 .asBitmap().dontAnimate(),它们在大多数情况下都会以某种方式提供帮助。

回复:: 我又试了一次(几乎一年的额外 XP)并想出了这个:

<ImageView android:scaleType="center" ... />

类似于我的其他解决方案和以下动画包装器:

...
    .fitCenter()
    .animate(new PaddingAnimationFactory<>(new DrawableCrossFadeFactory<GlideDrawable>(2000)))
    .into(imageView)
;

class PaddingAnimationFactory<T extends Drawable> implements GlideAnimationFactory<T> {
    private final DrawableCrossFadeFactory<T> realFactory;
    @Override public GlideAnimation<T> build(boolean isFromMemoryCache, boolean isFirstResource) {
        return new PaddingAnimation<>(realFactory.build(isFromMemoryCache, isFirstResource));
    }
}

class PaddingAnimation<T extends Drawable> implements GlideAnimation<T> {
    private final GlideAnimation<? super T> realAnimation;
    @Override public boolean animate(T current, final ViewAdapter adapter) {
        int width = current.getIntrinsicWidth();
        int height = current.getIntrinsicHeight();
        return realAnimation.animate(current, new PaddingViewAdapter(adapter, width, height));
    }
}

class PaddingViewAdapter implements ViewAdapter {
    @Override public Drawable getCurrentDrawable() {
        Drawable drawable = realAdapter.getCurrentDrawable();
        if (drawable != null) {
            int padX = Math.max(0, targetWidth - drawable.getIntrinsicWidth()) / 2;
            int padY = Math.max(0, targetHeight - drawable.getIntrinsicHeight()) / 2;
            if (padX != 0 || padY != 0) {
                drawable = new InsetDrawable(drawable, padX, padY, padX, padY);
            }
        }
        return drawable;
    }
    @Override public void setDrawable(Drawable drawable) {
        if (VERSION.SDK_INT >= VERSION_CODES.M && drawable instanceof TransitionDrawable) {
            // For some reason padding is taken into account differently on M than before in LayerDrawable
            // PaddingMode was introduced in 21 and gravity in 23, I think NO_GRAVITY default may play
            // a role in this, but didn't have time to dig deeper than this.
            ((TransitionDrawable)drawable).setPaddingMode(TransitionDrawable.PADDING_MODE_STACK);
        }
        realAdapter.setDrawable(drawable);
    }
}

省略了实现的琐碎部分,每个 class 的构造函数从参数初始化字段。 GitHub in TWiStErRob/glide-support 上提供完整代码。


如果您使用的是旧版本的 Glide(3.8.0 之前),可以通过以下方式实现相同的效果:

.fitCenter()
.placeholder(R.drawable.glide_placeholder)
.crossFade(2000)
.into(new GlideDrawableImageViewTarget(imageView) {
    @Override public void onResourceReady(GlideDrawable resource,
            GlideAnimation<? super GlideDrawable> animation) {
        super.onResourceReady(resource, new PaddingAnimation<>(animation));
    }
})

请注意这两个解决方案如何需要相同数量的 classes,但是 post-3.8.0 解决方案具有更好的关注点分离,并且可以将其缓存在变量中以防止分配.

我这样做如下所述:

想法是最初将比例类型设置为占位符所需的比例类型,并附加侦听器以在下载图像后再次将比例类型更改为下载图像所需的比例类型。

//ivBuilderLogo = Target ImageView
//Set the scale type to as required by your place holder
//ScaleType.CENTER_INSIDE will maintain aspect ration and fit the placeholder inside the image view
holder.ivBuilderLogo.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 

//AnimationDrawable is required when you are using transition drawables
//You can directly send resource id to glide if your placeholder is static
//However if you are using GIFs, it is better to create a transition drawable in xml 
//& use it as shown in this example
AnimationDrawable animationDrawable;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
     animationDrawable=(AnimationDrawable)context.getDrawable(R.drawable.anim_image_placeholder);
else
     animationDrawable=(AnimationDrawable)context.getResources().getDrawable(R.drawable.anim_image_placeholder);
animationDrawable.start();

Glide.with(context).load(logo_url)
                   .placeholder(animationDrawable)
                   .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource)
                        {
                           return false;
                        }

                        //This is invoked when your image is downloaded and is ready 
                        //to be loaded to the image view
                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource)
                        {   
                        //This is used to remove the placeholder image from your ImageView 
                        //and load the downloaded image with desired scale-type(FIT_XY in this case)
                        //Changing the scale type from 'CENTER_INSIDE' to 'FIT_XY' 
                        //will stretch the placeholder for a (very) short duration,
                        //till the downloaded image is loaded
                        //setImageResource(0) removes the placeholder from the image-view 
                        //before setting the scale type to FIT_XY and ensures that the UX 
                        //is not spoiled, even for a (very) short duration
                            holder.ivBuilderLogo.setImageResource(0);
                            holder.ivBuilderLogo.setScaleType(ImageView.ScaleType.FIT_XY);
                            return false;
                        }
                    })
                    .into( holder.ivBuilderLogo);

我的过渡可绘制对象(R.drawable.anim_image_placeholder):

(如果使用静态图片则不需要)

<?xml version="1.0" encoding="utf-8"?>
<animation-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/loading_frame1" android:duration="100" />
    <!--<item android:drawable="@drawable/loading_frame2" android:duration="100" />-->
    <item android:drawable="@drawable/loading_frame3" android:duration="100" />
    <!--<item android:drawable="@drawable/loading_frame4" android:duration="100" />-->
    <item android:drawable="@drawable/loading_frame5" android:duration="100" />
    <!--<item android:drawable="@drawable/loading_frame6" android:duration="100" />-->
    <item android:drawable="@drawable/loading_frame7" android:duration="100" />
    <!--<item android:drawable="@drawable/loading_frame8" android:duration="100" />-->
    <item android:drawable="@drawable/loading_frame9" android:duration="100" />
    <!--<item android:drawable="@drawable/loading_frame10" android:duration="100" />-->
</animation-list>