我是 Glide 库的新手,遵循此处的转换指南:https://github.com/bumptech/glide/wiki/Transformations
我正在尝试创建一个自定义转换,但是当我在 Transformation 类的 transform
方法中放置一个断线时,我可以看到它从未被调用。
下面是我的代码:
private static class CustomTransformation extends BitmapTransformation {
private Context aContext;
public CustomTransformation(Context context) {
super(context);
aContext = context;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return bitmapChanger(toTransform, 1080, (int) aContext.getResources().getDimension(R.dimen.big_image));
}
@Override
public String getId() {
return "some_id";
}
}
private static Bitmap bitmapChanger(Bitmap bitmap, int desiredWidth, int desiredHeight) {
float originalWidth = bitmap.getWidth();
float originalHeight = bitmap.getHeight();
float scaleX = desiredWidth / originalWidth;
float scaleY = desiredHeight / originalHeight;
//Use the larger of the two scales to maintain aspect ratio
float scale = Math.max(scaleX, scaleY);
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
//If the scaleY is greater, we need to center the image
if(scaleX < scaleY) {
float tx = (scale * originalWidth - desiredWidth) / 2f;
matrix.postTranslate(-tx, 0f);
}
return Bitmap.createBitmap(bitmap, 0, 0, (int) originalWidth, (int) originalHeight, matrix, true);
}
我试过用两种方式启动 Glide:
Glide.with(this).load(url).asBitmap().transform(new CustomTransformation(this)).into(imageView);
和
Glide.with(this).load(url).bitmapTransform(new CustomTransformation(this)).into(imageView);
但两者都不起作用。有任何想法吗?同样,我不是在寻找有关 Matrix 本身的建议,我只是不明白为什么根本没有调用 transform(...)
。谢谢!
最佳答案
您很可能遇到缓存问题。第一次编译和执行代码时,转换结果已缓存,因此下次不必将其应用于同一源图像。
每个转换都有一个 getId()判断转换结果是否改变的方法。通常转换不会改变,但要么应用,要么不应用。您可以在开发过程中在每次构建时更改它,但这可能很乏味。
要解决此问题,您可以将以下两个调用添加到您的 Glide 加载行:
// TODO remove after transformation is done
.diskCacheStrategy(SOURCE) // override default RESULT cache and apply transform always
.skipMemoryCache(true) // do not reuse the transformed result while running
第一个可以改成NONE,但是每次都要等url从网络加载,而不是直接从手机上读取图片。例如,如果您可以导航到和离开有问题的转换并且想要调试它,则第二个很有用。它有助于在每次加载后不需要重新启动来清除内存缓存。
完成转换的开发后,不要忘记删除它们,因为它们对生产性能影响很大,应该在经过深思熟虑后才使用,如果有的话。
注意事项
看起来你试图在加载之前将图像调整到特定大小,你可以使用 .override(width, height)
结合 .centerCrop()
/.fitCenter()
/.dontTransform()
为此。
关于android - Glide 库中的 BitmapTransformation 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30768505/