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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章