2012-07-23 93 views
6

我有一個自定義視圖,我使用onDraw()繪製到我的畫布上。我正在畫布上畫一幅圖片。如何將圖像橫向或倒置?

我想顛倒圖像有點像在水平線上翻轉作爲參考。這與將圖像旋轉180度或-180度不一樣。

同樣,我想鏡像或翻轉sidways,即與垂直線,因爲它的樞軸或參考。這同canvas.rotate()提供的不一樣。

我在想如何去做。我應該使用矩陣還是畫布提供了像「旋轉」那樣的任何方法。

謝謝。

回答

23

你不能用Canvas直接做。在繪製之前,您需要實際修改位圖(使用矩陣)。幸運的是,這是一個非常簡單的代碼:

public enum Direction { VERTICAL, HORIZONTAL }; 

/** 
    Creates a new bitmap by flipping the specified bitmap 
    vertically or horizontally. 
    @param src  Bitmap to flip 
    @param type  Flip direction (horizontal or vertical) 
    @return   New bitmap created by flipping the given one 
         vertically or horizontally as specified by 
         the <code>type</code> parameter or 
         the original bitmap if an unknown type 
         is specified. 
**/ 
public static Bitmap flip(Bitmap src, Direction type) { 
    Matrix matrix = new Matrix(); 

    if(type == Direction.VERTICAL) { 
     matrix.preScale(1.0f, -1.0f); 
    } 
    else if(type == Direction.HORIZONTAL) { 
     matrix.preScale(-1.0f, 1.0f); 
    } else { 
     return src; 
    } 

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

謝謝@ aleks-g – 2012-07-23 16:47:58

+0

感謝您的代碼片段。我想要一個翻轉的圖像,並使用setImageResource,我簡單地替換爲:imageView.setImageBitmap(flip(BitmapFactory.decodeResource(getResources(),R.id.someimage),Direction.HORIZONTAL)); – 2013-04-08 17:35:39

+1

我知道這是非常古老的,但這只是保存了我的培根。謝謝! – LokiSinclair 2013-11-20 15:40:01