標籤:android style blog http color os sp on div
Matrix ,中文裡叫矩陣,高等數學裡有介紹,在影像處理方面,主要是用於平面的縮放、平移、旋轉等操作。
首先介紹一下矩陣運算。加法和減法就不用說了,太簡單了,對應位相加就好。影像處理,主要用到的是乘法 。下面是一個乘法的公式:
在 Android 裡面, Matrix 由 9 個 float 值構成,是一個 3*3 的矩陣。如。
沒專業工具,畫的挺難看。解釋一下,上面的 sinX 和 cosX ,表示旋轉角度的 cos 值和 sin 值,注意,旋轉角度是按順時針方向計算的。 translateX 和 translateY 表示 x 和 y 的平移量。 scale 是縮放的比例, 1 是不變, 2 是表示縮放 1/2 ,這樣子。
下面在 Android 上試試 Matrix 的效果。
public class MyView extends View { private Bitmap mBitmap; private Matrix mMatrix = new Matrix(); public MyView(Context context) { super(context); initialize(); } private void initialize() { mBitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap(); float cosValue = (float) Math.cos(-Math.PI/6); float sinValue = (float) Math.sin(-Math.PI/6); mMatrix.setValues( new float[]{ cosValue, -sinValue, 100, sinValue, cosValue, 100, 0, 0, 2}); } @Override protected void onDraw(Canvas canvas) { // super.onDraw(canvas); //當然,如果介面上還有其他元素需要繪製,只需要將這句話寫上就行了。 canvas.drawBitmap(mBitmap, mMatrix, null); } }
運行結果如下:
以左上方為頂點,縮放一半,逆時針旋轉 30 度,然後沿x 軸和 y 軸分別平移50 個像素,代碼 裡面寫的是 100,為什麼是平移 50 呢,因為縮放了一半。
大家可以自己設定一下 Matrix 的值,或者嘗試一下兩個 Matrix 相乘,得到的值設定進去,這樣才能對 Matrix 更加熟練。 這裡講的直接賦值的方式也許有點不好理解,不過還好, andrid 提供了對矩陣的更方便的方法,下一篇介紹 。
Android 畫圖之 Matrix(一)