Android游戲開(kāi)發(fā)之十:Bitmap位圖的旋轉(zhuǎn)
Android為圖形的旋轉(zhuǎn)和變化提供了方便的矩陣Matrix類(lèi)。Maxtrix類(lèi)的setRotate方法接受圖形的變換角度和縮放,而后可以 由Bitmap類(lèi)的createBitmap方法的一個(gè)重載函數(shù)接受Maxtrix對(duì)象,此createBitmap方法原型如下:
public static Bitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)
參數(shù)的具體意義:
source:源bitmap對(duì)象
x:源坐標(biāo)x位置
y:源坐標(biāo)y位置
width:寬度
height:高度
m:接受的maxtrix對(duì)象,如果沒(méi)有可以設(shè)置為null
filter:該參數(shù)僅對(duì)maxtrix包含了超過(guò)一個(gè)翻轉(zhuǎn)才有效。
下面給大家一個(gè)比較經(jīng)典的例子,rotate方法是靜態(tài)方法可以直接調(diào)用,參數(shù)為源Bitmap對(duì)象,參數(shù)二為旋轉(zhuǎn)的角度,從0~360,返回值為新的Bitmap對(duì)象。其中具體的寬高可以調(diào)整。
- public static Bitmap rotate(Bitmap b, int degrees) {
- if (degrees != 0 && b != null) {
- Matrix m = new Matrix();
- m.setRotate(degrees,
- (float) b.getWidth() / 2, (float) b.getHeight() / 2);
- try {
- Bitmap b2 = Bitmap.createBitmap(
- b, 0, 0, b.getWidth(), b.getHeight(), m, true);
- if (b != b2) {
- b.recycle(); //Android開(kāi)發(fā)網(wǎng)再次提示Bitmap操作完應(yīng)該顯示的釋放
- b = b2;
- }
- } catch (OutOfMemoryError ex) {
- // 建議大家如何出現(xiàn)了內(nèi)存不足異常,***return 原始的bitmap對(duì)象。.
- }
- }
- return b;
- }
在后面的教程中我們會(huì)給出Matrix類(lèi)相關(guān)的一些其他的應(yīng)用實(shí)例。