Matrix(2)Android繪圖
Matrix(1)在最后一篇Android繪圖中描述了Matrix的原理和計(jì)算方法,這涉及到高數(shù),這有點(diǎn)難以理解。幸運(yùn)的是,安卓帶來(lái)了一系列關(guān)于Matrix操作的信息。
列出方便的接口。
Matrix的操作,共分為translate(平移),rotate(轉(zhuǎn)動(dòng)),scale四種類型:(縮放)和skew(傾斜),每一種轉(zhuǎn)換都在
在API中,Android帶來(lái)了set, 除translate外,post和pre三種操作方法,其它三種操作都能指定中心點(diǎn)。
post是當(dāng)前矩陣乘以參數(shù)給出的后乘矩陣。post可以連續(xù)多次使用,以完成所需的整個(gè)轉(zhuǎn)換。例如,旋轉(zhuǎn)一張圖片
轉(zhuǎn)動(dòng)30度,然后轉(zhuǎn)移到(100,100)區(qū)域,然后就可以這樣做:
1. Matrix m = newMatrix();
2.
3. m.postRotate(30);
4.
5. m.postTranslate(100, 100);
通過(guò)這種方式達(dá)到預(yù)期的效果。
pre是前乘,參數(shù)給出的矩陣乘以當(dāng)前矩陣。因此,操作發(fā)生在當(dāng)前矩陣的前面。例如,如果使用pre,上面的例子
,就要這樣:
1. Matrix m = newMatrix();
2.
3. m.setTranslate(100, 100);
4.
5. m.preRotate(30);
1. packagechroya.demo.graphics;
2.
3. importandroid.content.Context;
4. importandroid.graphics.Bitmap;
5. importandroid.graphics.Canvas;
6. importandroid.graphics.Matrix;
7. importandroid.graphics.Rect;
8. importandroid.graphics.drawable.BitmapDrawable;
9. importandroid.util.DisplayMetrics;
10. importandroid.view.MotionEvent;
11. importandroid.view.View;
12.
13. publicclassMyView extendsView {
14.
15. privateBitmap mBitmap;
16. privateMatrix mMatrix = newMatrix();
17.
18. publicMyView(Context context) {
19. super(context);
20. initialize();
21. }
22.
23. privatevoidinitialize() {
24.
25. Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();
26. mBitmap = bmp;
27.
28. mMatrix.setScale(100f/bmp.getWidth(), 100f/bmp.getHeight());
29. //平移到(100,100)
30. mMatrix.postTranslate(100, 100);
31. 以(100,100)為中心的//傾斜x和y軸。32. mMatrix.postSkew(0.2f, 0.2f, 100, 100);
33. }
34.
35. @OverrideprotectedvoidonDraw(Canvas canvas) {
36. // super.onDraw(canvas); //如果界面上有其它元素需要繪制,只要把這句話寫下來(lái)就行了。37.
38. canvas.drawBitmap(mBitmap, mMatrix, null);
39. }
40. }
運(yùn)行效果如下:
。
本文僅代表作者觀點(diǎn),版權(quán)歸原創(chuàng)者所有,如需轉(zhuǎn)載請(qǐng)?jiān)谖闹凶⒚鱽?lái)源及作者名字。
免責(zé)聲明:本文系轉(zhuǎn)載編輯文章,僅作分享之用。如分享內(nèi)容、圖片侵犯到您的版權(quán)或非授權(quán)發(fā)布,請(qǐng)及時(shí)與我們聯(lián)系進(jìn)行審核處理或刪除,您可以發(fā)送材料至郵箱:service@tojoy.com


