不久前,我們有一個問題是如何用 Glide 旋轉圖像,因為 Picasso 提供了這個方法 [out-of-the-box](https://futurestud.io/blog/picasso-image-rotation-and-transformation)。不幸的是,Glide 并不提供這樣的小方法的調用,但是在這個博客中我們將會告訴你怎么做的跟它一樣簡單。
如果你需要關于 Glide 的更多內容,瀏覽我們這些博客列表:
**如何用 Glide 旋轉圖片**?
事實上,[android.graphics.Matrix](https://developer.android.com/reference/android/graphics/Matrix.html?hl=zh-cn) 類提供了我們所需要的準確辦法(甚至更多辦法)。這個代碼片段就是用來旋轉圖像的:
~~~
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;
}
}
~~~
如果你不知道上面這個類發生了,去看看我們介紹的 [Custom Transformations](https://futurestud.io/blog/glide-custom-transformation),它將告訴你所有你要知道的。
最后,讓我們看看新的轉換的實例:
~~~
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 中旋轉的圖片,即使它沒有直接在庫中提供。如果這對你來說有用的,在評論中讓我們知道唄!
- 前言
- 一開始
- 二加載進階
- 三ListAdapter(ListView, GridView)
- 四占位符 和 漸現動畫
- 五圖片重設大小 和 縮放
- 六顯示 Gif 和 Video
- 七緩存基礎
- 八請求優先級
- 九縮略圖
- 十回調:SimpleTarget 和 ViewTarget 用于自定義視圖類
- 十一加載圖片到通知欄和應用小部件中
- 十二異常:調試和錯誤處理
- 十三自定義轉換
- 十四用 animate() 自定義動畫
- 十五集成網絡棧
- 十六用 Module 自定義
- 十七Module 實例:接受自簽名證書的 HTTPS
- 十八Module 實例:自定義緩存
- 十九Module 實例:用自定義尺寸優化加載的圖片
- 二十動態使用 Model Loader
- 二十一如何旋轉圖像
- 二十二系列綜述