Glide入门教程(19)如何旋转图片

       在Picasso中,提供了旋转图片的方法,但是Glide没有类似的方法可调用。实际上android.graphics.Matrix类可以满足我们的需求。旋转图片的代码如下:

1
2
3
4
5
6
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里包装它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
}
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 );
}

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

       需要注意的是,上面的方法有一个问题要注意,如果旋转的角度并不是90度的倍数,旋转后的图片会有一个很难看的黑色背景,如下图所示:

旋转角度带有黑色背景

       需要配合ClearBackGroundTransform使用,ClearBackGroundTransform中通过Bitmap.Config.ARGB_8888消除了黑色背景。

       另外使用Matrix旋转加Canvas重新绘制也会有问题,图片无法适应大小;而使用TransformationUtils,只能旋转90度的倍数。

       代码详见Github上的GlideTest

参考资料:
签到钱就到 Glide入门教程——21.如何旋转图片

Fork me on GitHub