android – Glide:加载drawable但不缩放占位符

前端之家收集整理的这篇文章主要介绍了android – Glide:加载drawable但不缩放占位符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法使用Glide来分配一个占位符,但是将这个图像保持原来的大小?
我有一个可变大小的 ImageView(取决于传入的图像),我在调用Glide.with().load().into()之前设置,我想使用占位符,但不希望PH被调整为ImageView的大小,我希望它保持原来的大小.
到目前为止,我找不到办法.

解决方法

Re: Gregs comment
我给了另一个镜头(几乎一年的额外的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,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);
    }
}

省略实现的平凡部分,每个类的构造函数从参数初始化字段.完整代码可在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));
    }
})

请注意,两个解决方案需要相同数量的类,但是后3.8.0解决方案有更好的分离问题,并且可以缓存在一个变量中以防止分配.

原文链接:https://www.f2er.com/android/312273.html

猜你在找的Android相关文章