Glide - 如何旋轉圖像

來自: http://mrfu.me/2016/02/28/Glide_How_to_Rotate_Images/

不久前,我們有一個問題是如何用 Glide 旋轉圖像,因為 Picasso 提供了這個方法 out-of-the-box 。不幸的是,Glide 并不提供這樣的小方法的調用,但是在這個博客中我們將會告訴你怎么做的跟它一樣簡單。

如果你需要關于 Glide 的更多內容,瀏覽我們這些博客列表:

Glide 系列瀏覽

  1. 開始!
  2. 加載進階
  3. ListAdapter(ListView, GridView)
  4. 占位符 和 漸現動畫
  5. 圖片重設大小 和 縮放
  6. 顯示 Gif 和 Video
  7. 緩存基礎
  8. 請求優先級
  9. 縮略圖
  10. 回調:SimpleTarget 和 ViewTarget 用于自定義視圖類
  11. 加載圖片到通知欄和應用小部件中
  12. 異常:調試和錯誤處理
  13. 自定義轉換
  14. 用 animate() 自定義動畫
  15. 集成網絡棧
  16. 用 Module 自定義 Glide
  17. Module 實例:接受自簽名證書的 HTTPS
  18. Module 實例:自定義緩存
  19. Module 實例:用自定義尺寸優化加載的圖片
  20. 動態使用 Model Loader
  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;
    }
}

如果你不知道上面這個類發生了,去看看我們介紹的 Custom Transformations ,它將告訴你所有你要知道的。

最后,讓我們看看新的轉換的實例:

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 中旋轉的圖片,即使它沒有直接在庫中提供。如果這對你來說有用的,在評論中讓我們知道唄!

</div>

 本文由用戶 KatharinaAl 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!