Glide入门教程——21.如何旋转图片

Glide — 如何旋转图片

原文:How to Rotate Images
作者:Norman Peitek
翻译:Dexter0218

不久前,我们有一个问题:如何用Glide旋转图像,由于Picasso提供此即学即用的功能。不幸的是,Glide不提供这一点方法调用,但在这个博客文章中,我们将展示如何几乎一样容易地使它。
如果您需要更多Glide的内容,浏览我们博客文章列表上的主题:

Glide 系列概览

  1. 入门简介
  2. 高级加载
  3. 适配器(ListView, GridView)
  4. 占位图& 淡入淡出动画
  5. 图片大小 & 缩放
  6. 播放GIF & 视频
  7. 缓存基础
  8. 请求优先级
  9. 缩略图
  10. 回调:定制view中使用SimpleTarget和ViewTarget
  11. 通知栏和桌面小控件的图片加载
  12. 异常: 调试和报错处理
  13. 自定义变换
  14. 用animate()定制动画
  15. 整合网络协议栈
  16. 用Modules定制Glide
  17. Glide Module 案例: 接受自签名HTTPS证书
  18. Glide Module 案例: 自定义缓存
  19. Glide Module 案例: 通过加载自定义大小图片优化
  20. 动态使用 Model Loaders
  21. 如何旋转图片
  22. 系列综述

如何用Glide旋转图片

实际上android.graphics.Matrix类正好提供了我们需要的。旋转图片的代码实际上非常直截了当:

Bitmap toTransform = ... // your bitmap source

Matrix matrix = new Matrix();  
matrix.postRotate(rotateRotationAngle);

Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);  

为了让它对我们更有用,特别是在使用Glide的情况下,我们在一个BitmapTransformation里包装它:

public class RotateTransformation extends BitmapTransformation {

    private float rotateRotationAngle = 0f;

    public RotateTransformation(Context context, float rotateRotationAngle) {
        super( context );

        this.rotateRotationAngle = rotateRotationAngle;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Matrix matrix = new Matrix();

        matrix.postRotate(rotateRotationAngle);

        return Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);
    }

    @Override
    public String getId() {
        return "rotate" + rotateRotationAngle;
    }
}

如果你还没有明白这个类里发生了什么,回顾看一下在自定义变换那篇文章的介绍,你会看到你需要知道的东西。

最后,我们看看新变换的几个例子:

private void loadImageOriginal() {  
    Glide
        .with( context )
        .load( eatFoodyImages[0] )
        .into( imageView1 );
}

private void loadImageRotated() {  
    Glide
        .with( context )
        .load( eatFoodyImages[0] )
        .transform( new RotateTransformation( context, 90f ))
        .into( imageView3 );
}

当然,你可以改变第二个参数去设置要被旋转多少角度。你可以动态地设置它!

你需要用Glide旋转图像,这里提供所有的代码和知识,即使它没有在库里直接提供。如果这对你有用,我们会对你在下面友好评论表示感激!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容