android畫圖之Matrix(二)

 

上一篇Android畫圖之Matrix(一) 講了一下Matrix的原理和運算方法,涉及到高等數學,有點難以理解。還好Android裏面提供了對Matrix操作的一系

列方便的接口。


    Matrix的操作,總共分爲translate(平移),rotate(旋轉),scale(縮放)和skew(傾斜)四種,每一種變換在

Android的API裏都提供了set, post和pre三種操作方式,除了translate,其他三種操作都可以指定中心點。


    set是直接設置Matrix的值,每次set一次,整個Matrix的數組都會變掉。


    post是後乘,當前的矩陣乘以參數給出的矩陣。可以連續多次使用post,來完成所需的整個變換。例如,要將一個圖片旋
轉30度,然後平移到(100,100)的地方,那麼可以這樣做:

Matrix m = new Matrix();   

m.postRotate(30);   

m.postTranslate(100, 100);    


     pre是前乘,參數給出的矩陣乘以當前的矩陣。所以操作是在當前矩陣的最前面發生的。例如上面的例子,如果用pre的話

,就要這樣:

Matrix m = new Matrix();   

m.setTranslate(100, 100);   
 
m.preRotate(30);  


旋轉、縮放和傾斜都可以圍繞一箇中心點來進行,如果不指定,默認情況下,是圍繞(0,0)點來進行。


    下面是一個例子。

package chroya.demo.graphics;   
  
import android.content.Context;   
import android.graphics.Bitmap;   
import android.graphics.Canvas;   
import android.graphics.Matrix;   
import android.graphics.Rect;   
import android.graphics.drawable.BitmapDrawable;   
import android.util.DisplayMetrics;   
import android.view.MotionEvent;   
import android.view.View;   
  
public class MyView extends View {   
       
    private Bitmap mBitmap;   
    private Matrix mMatrix = new Matrix();   
       
    public MyView(Context context) {   
        super(context);   
        initialize();   
    }   
  
    private void initialize() {   
           
        Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();    
       mBitmap = bmp;   
        /*首先,將縮放爲100*100。這裏scale的參數是比例。有一點要注意,如果直接用100/  
   bmp.getWidth()的話,會得到0,因爲是整型相除,所以必須其中有一個是float型的,直接用100f就好。*/  
        mMatrix.setScale(100f/bmp.getWidth(), 100f/bmp.getHeight());   
                //平移到(100,100)處   
        mMatrix.postTranslate(100, 100);   
                //傾斜x和y軸,以(100,100)爲中心。   
        mMatrix.postSkew(0.2f, 0.2f, 100, 100);   
    }   
       
    @Override protected void onDraw(Canvas canvas) {   
//      super.onDraw(canvas);  //如果界面上還有其他元素需要繪製,只需要將這句話寫上就行了。   
           
        canvas.drawBitmap(mBitmap, mMatrix, null);   
    }   
}  


運行結果:

發佈了28 篇原創文章 · 獲贊 22 · 訪問量 96萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章