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)的地方,那么可以这样做:
Java代码
Matrix m = new Matrix();

m.postRotate(30);

m.postTranslate(100, 100);


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

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

,就要这样:
Java代码
Matrix m = new Matrix();

m.setTranslate(100, 100);

m.preRotate(30);
旋转、缩放和倾斜都可以围绕一个中心点来进行,如果不指定,默认情况下,是围绕(0,0)点来进行。

下面给出一个例子。
Java代码
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);
}
}
运行效果如下:

Android画图之Matrix(二)


红色的x和y表示倾斜的角度,下面是x,上面是y。看到了没,Matrix就这么简单 。

更多相关文章

  1. Android 封装的数据库管理操作类
  2. Android SQLite数据库操作
  3. 分析:Android和Linux正在合并为一种操作系统
  4. Android sd卡操作的一些坑
  5. 谷歌正式发布Android 2.2手机操作平台
  6. 浅析Android手机卫士接收短信指令执行相应操作
  7. SQLite语法与Android数据库操作

随机推荐

  1. Android(安卓)Gradle Plugin指南(三)----依
  2. android——android中测试框架AndroidTes
  3. android8.0 launcher改透明
  4. Android实现振动效果
  5. 【转】Android(安卓)字符串的加密和解密
  6. Android(安卓)xutils 登录 注册
  7. Android(安卓):Process xxxxx (pid xxxxx)
  8. 2011.07.05——— android notifyDataSet
  9. android 获取 imei号码
  10. Android中回调接口的使用