您的位置:首页 > 其它

Glide加载图片之自定义转换

2016-08-24 14:46 381 查看
Transformations

转换可以在图片显示出来之前对其做一些处理。例如,如果您需要对一个要显示图片做灰度处理,但只有原始fully-colored的版本,您可以使用一个transformation操作图片将其转变为灰度图片。不要误会我的意思哦,转换不是仅仅局限于颜色转换,你可以改变图片的任何属性:大小,界限,颜色,像素点等等。Glide已经提供了两个转换,我们之前已经用过了:fitCenter和centerCrop,这两种转换类似,下面我们不再讲述这两种变换。

实现你自己定义的转换

为了应用自己自定义的转换,您需要创建一个新类,它实现Transformation接口。您需要实现的方法很复杂,你需要对Glide内部有相当的洞察力来使它工作得更好。如果你只是想改变常规的位图图片(没有gif /视频),我们建议使用抽象BitmapTransformation类。它简化了实现不少,应该覆盖95%的用例。

因此,让我们看一个示例BitmapTransformation实现。如果你经常读这个博客,你知道我们最喜欢的转换是模糊图像渲染脚本。我们几乎可以使用相同的代码来实现Glide的转换。因为我们必须扩展BitmapTransformation类,我们已经有我们的框架:

public class BlurTransformation extends BitmapTransformation {

public BlurTransformation(Context context) {
super( context );
}

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return null; // todo
}

@Override
public String getId() {
return null; // todo
}
}


我们之前的模糊图像渲染脚本:

public class BlurTransformation extends BitmapTransformation {

private RenderScript rs;

public BlurTransformation(Context context) {
super( context );

rs = RenderScript.create( context );
}

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );

// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(
rs,
blurredBitmap,
Allocation.MipmapControl.MIPMAP_FULL,
Allocation.USAGE_SHARED
);
Allocation output = Allocation.createTyped(rs, input.getType());

// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);

// Set the blur radius
script.setRadius(10);

// Start the ScriptIntrinisicBlur
script.forEach(output);

// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);

toTransform.recycle();

return blurredBitmap;
}

@Override
public String getId() {
return "blur";
}
}


再有,如果你对transform()方法块不理解,请阅读[如何使用Android的模糊图像有效地渲染脚本](https://futurestud.io/blog/how-to-blur-images-efficiently-with-androids-renderscript

getId()方法是对这个特定的转换的一个独特的标识符。Glide使用它作为缓存系统的一部分。确保它独一无二,以避免意想不到的问题。

Apply a Single Transformation

通常,Glide的连贯接口允许链接的方法。然而,随着转换情况并非如此。确保你只调用.transform()或.bitmapTransform()一次,否则之前的配置将被覆盖。然而,你仍然可以申请多个转换通过多个对象作为参数转变成.transform()(或.bitmapTransform()):

Glide
.with( context )
.load( eatFoodyImages[1] )
.transform( new GreyscaleTransformation( context ), new BlurTransformation( context ) )
.into( imageView2 );


在这个代码片段中,我们先使用了一个灰度转换,然后使用了一个模糊转换。Glide都会自动执行这两种转换。很不错吧!

提示:当您使用转换的时候您不能使用.centerCrop()或.fitCenter()。

Apply Multiple Transformations

如果您已经确定您的应用中将会用到哪些转换,你可以花费点时间看一下下面的转换库:glide-transformations。它提供了一个整体的集合的各种Glide转换。值得你去检查一下你的想法是否已经实现了。

Collection of Glide Transformations

Setup for Glide Transformations

Usage of Glide Transformations
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  glide
相关文章推荐