Android畫圖之Matrix(二)

來源:互聯網
上載者:User

參考:http://www.iteye.com/topic/713869

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

public class ViewActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(new MyView(this));    }    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軸,以(100,100)為中心。       mMatrix.postSkew(0.5f, 0f, 100, 100);     //傾斜y軸 以(100,100)為中心。//    mMatrix.postSkew(0f, 0.5f, 100, 100);//    mMatrix.postSkew(0.2f, 0.2f, 100, 100);    }        @Override protected void onDraw(Canvas canvas) {//    super.onDraw(canvas);  //如果介面上還有其他元素需要繪製,只需要將這句話寫上就行了。        canvas.drawBitmap(mBitmap, mMatrix, null);    }    }}

效果:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.