Android 畫圖之Matrix(二)

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   color   os   使用   sp   

  上一篇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)點來進行。

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);    }}

運行效果如下:

 紅色的x和 y表示傾斜的角度,下面是 x,上面是 y。看到了沒,Matrix就這麼簡單 。

Android 畫圖之Matrix(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.