0
点赞
收藏
分享

微信扫一扫

Android画图之Matrix(二)


上一篇Android画图之Matrix(一) 讲了一下Matrix的原理和运算方法,涉及到高等数学,有点难以理解。还好Android里面提供了对Matrix操作的一系

列方便的接口。

    Matrix的操作,总共分为translate(平移),rotate(旋转),scale(缩放)和skew(倾斜)四种,每一种变换在

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

   

    post是后乘,当前的矩阵乘以参数给出的矩阵。可以连续多次使用post,来完成所需的整个变换。例如,要将一个图片旋
转30度,然后平移到(100,100)的地方,那么可以这样做:

Android画图之Matrix(二)_android



1. Matrix m = newMatrix();  
2.  
3. m.postRotate(30);  
4.  
5. m.postTranslate(100, 100);



这样就达到了想要的效果。

    pre是前乘,参数给出的矩阵乘以当前的矩阵。所以操作是在当前矩阵的最前面发生的。例如上面的例子,如果用pre的话

,就要这样:


Android画图之Matrix(二)_android



1. Matrix m = newMatrix();  
2.  
3. m.setTranslate(100, 100);  
4.  
5. m.preRotate(30);


 

Android画图之Matrix(二)_android


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.                //倾斜x和y轴,以(100,100)为中心。 
32.        mMatrix.postSkew(0.2f, 0.2f, 100, 100);  
33.    }  
34.      
35.    @OverrideprotectedvoidonDraw(Canvas canvas) {  
36. //      super.onDraw(canvas);  //如果界面上还有其他元素需要绘制,只需要将这句话写上就行了。 
37.          
38.        canvas.drawBitmap(mBitmap, mMatrix, null);  
39.    }  
40. }


运行效果如下:


Android画图之Matrix(二)_Android_04

  。

举报

相关推荐

0 条评论