Android 圖像繪製之Matrix 的使用

Android 中擁有衆多的圖像繪製的函數,而功能最強大的就是 drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)

Android官方文檔的描述爲Draw the bitmap using the specified matrix.翻譯成中文就是:用特定的矩陣來畫圖。而在其中最重要的參數就是 matrix

圖片的平移:就是設定其中心位置的變換,我們可是使用這樣的兩個函數做到:

setTranslate(float dx, float dy)

postTranslate(float dx, float dy)

查看更多精彩圖片

對於矩陣變換此處的前乘和後乘我們不做過多的介紹,我們按照一種固定的變化順序來進行變化,故全部使用後乘來解決。即全爲post開頭的方法,而set開頭的方法是對我們已經做過的變換進行重置。好吧,實例說明一切:

                    matrix.setTranslate(100, 100);

                    canvas.drawBitmap(bitmap,matrix,mPaint);

查看更多精彩圖片

圖片的旋轉:同樣的四個函數:

postRotate(float degrees)

postRotate(float degrees, float px, float py)

setRotate(float degrees)

setRotate(float degrees, float px, float py)

其中的pxpy是代表旋轉的中心點的意思,如果不指定中心點的話,默認是(0,0)點進行旋轉。

              matrix.setTranslate(100, 100);

                matrix.postRotate(90,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                canvas.drawBitmap(bitmap,matrix,mPaint);

查看更多精彩圖片

圖片的縮放:

postScale(float sx, float sy)

postScale(float sx, float sy, float px, float py)

setScale(float sx, float sy, float px, float py)

setScale(float sx, float sy)

其中的參數的情況與圖片旋轉的情況一樣,上實例:

                  matrix.setTranslate(100, 100);

                  matrix.postRotate(90,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  matrix.postScale(2,2,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  canvas.drawBitmap(bitmap,matrix,mPaint);

查看更多精彩圖片

圖片的反轉:這個情況androidAPI裏面沒有給我們直接寫出,但是我們可以使用圖片縮放的函數來實現。看實例吧:

                  matrix.setTranslate(100, 100);

                  matrix.postRotate(90,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  matrix.postScale(2,2,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  matrix.postScale(-1f,-1f,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  canvas.drawBitmap(bitmap,matrix,mPaint);

查看更多精彩圖片

基本上通過如上的變換就可以畫出想要的圖像了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章