版权声明:个人原创,欢迎转载。 https://blog.csdn.net/chuyangchangxi/article/details/90769249
Android使用Glide实现图片变换
上一开发阶段《iOS Messages显示图片功能分析》,讨论了iOS Messages如何显示图片。
现在开始着手实现图片显示功能。
一、目标
找寻实现图片显示功能的技术方案。
二、功能需求
- 图片处理过程
过程 | 描述 |
---|---|
加载图片 | 从File或者Uri加载图片为Bitmap |
图片变换 | 对原始Bitmap进行一系列变换,转换为目标Bitmap |
缓存图片 | 对目标Bitmap进行缓存,再次加载时直接使用缓存图片 |
- 图片变换
变换 | 描述 |
---|---|
CenterCrop | 裁剪图片中心区域图片,以处理图片尺寸超过显示尺寸的情况。 |
Mask | 使用Mask图片作为遮罩,只显示遮罩区域图片 |
三、实现方案
1. Glide
Glide完美实现了图片处理功能,从加载图片到变换到缓存,样样俱全。
项目 | 描述 |
---|---|
bumptech/glide | 完美的图片加载框架 |
wasabeef/glide-transformations | 超强的图片变换功能 |
2. transformations
glide和glide-transformations提供的图片变换功能。
- glide
变换 | 描述 |
---|---|
CenterCrop | 中间裁剪 |
CenterInside | |
FitCenter | |
CircleCrop | 圆形 |
RoundedCorners | 圆角矩形 |
- glide-transformations
变换 | 描述 |
---|---|
MaskTransformation | 遮罩 |
BlurTransformation | |
SupportRSBlurTransformation | |
RoundedCornersTransformation | |
CropTransformation | |
CropCircleTransformation | |
CropSquareTransformation | |
GrayscaleTransformation | |
ColorFilterTransformation | |
GPUFilterTransformation | 需要gpuimage支持 |
KuwaharaFilterTransformation | |
ToonFilterTransformation | |
ContrastFilterTransformation | |
InvertFilterTransformation | |
SepiaFilterTransformation | |
PixelationFilterTransformation | |
BrightnessFilterTransformation | |
SketchFilterTransformation | |
SwirlFilterTransformation | |
VignetteFilterTransformation |
四、实现过程
得益于Glide的强大功能,只需要计算目标显示尺寸和气泡形状2个参数,剩下的工作量只有不到20行代码。
1. 设置控件尺寸
public void onBind(PhotoItem item, int position) {
Point targetSize = getTargetSize(getContext(), item.getWidth(), item.getHeight());
{
int width = targetSize.x;
int height = targetSize.y;
photoView.getLayoutParams().width = width;
photoView.getLayoutParams().height = height;
photoView.setBackgroundResource(getBubble(item));
photoView.setPadding(0, 0, 0, 0);
}
{
RequestOptions options = createRequestOptions(item, targetSize);
Glide.with(itemView)
.load(item.getUri())
.apply(options)
.listener(new PictureListener())
.into(photoView);
}
}
2. 应用图片变换
需要组合CenterCrop
和MaskTransformation
来完成图片变化。
RequestOptions createRequestOptions(PhotoItem item, Point targetSize) {
RequestOptions options = new RequestOptions();
// picture size
int width = targetSize.x;
int height = targetSize.y;
{
options.override(width, height);
options.signature(new ObjectKey(item.getSignature()));
options.transforms(new CenterCrop(), new MaskTransformation(getBubble(item)));
}
return options;
}
五、开发过程回顾
- 明确功能需求
- 选择合适的技术方案
最终方案——glide和glide-transformations。
六、接下来
整合技术方案,实现最终效果。
七、Finally
~若见诸相非相~即见如来~