Glide — 如何旋轉圖片
原文:How to Rotate Images
作者:Norman Peitek
翻譯:Dexter0218
不久前,我們有一個問題:如何用Glide旋轉圖像,由于Picasso提供此即學即用的功能。不幸的是,Glide不提供這一點方法調用,但在這個博客文章中,我們將展示如何幾乎一樣容易地使它。
如果您需要更多Glide的內容,瀏覽我們博客文章列表上的主題:
Glide 系列概覽
- 入門簡介
- 高級加載
- 適配器(ListView, GridView)
- 占位圖& 淡入淡出動畫
- 圖片大小 & 縮放
- 播放GIF & 視頻
- 緩存基礎
- 請求優先級
- 縮略圖
- 回調:定制view中使用SimpleTarget和ViewTarget
- 通知欄和桌面小控件的圖片加載
- 異常: 調試和報錯處理
- 自定義變換
- 用animate()定制動畫
- 整合網絡協議棧
- 用Modules定制Glide
- Glide Module 案例: 接受自簽名HTTPS證書
- Glide Module 案例: 自定義緩存
- Glide Module 案例: 通過加載自定義大小圖片優化
- 動態使用 Model Loaders
- 如何旋轉圖片
- 系列綜述
如何用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旋轉圖像,這里提供所有的代碼和知識,即使它沒有在庫里直接提供。如果這對你有用,我們會對你在下面友好評論表示感激!