Android画图之Matrix(一)
来源:互联网 发布:exo知乎 编辑:程序博客网 时间:2024/05/21 14:42
Matrix ,中文里叫矩阵,高等数学里有介绍,在图像处理方面,主要是用于平面的缩放、平移、旋转等操作。
首先介绍一下矩阵运算。加法和减法就不用说了,太简单了,对应位相加就好。图像处理,主要用到的是乘法 。下面是一个乘法的公式:
在 Android 里面, Matrix 由 9 个 float 值构成,是一个 3*3 的矩阵。如下图。
没专业工具,画的挺难看。解释一下,上面的 sinX 和 cosX ,表示旋转角度的 cos 值和 sin 值,注意,旋转角度是按顺时针方向计算的。 translateX 和 translateY 表示 x 和 y 的平移量。 scale 是缩放的比例, 1 是不变, 2 是表示缩放 1/2 ,这样子。
下面在 Android 上试试 Matrix 的效果。
Java代码
- 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);
- }
- }
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(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix(一)
- android画图之Matrix(一)
- Android画图之Matrix(一)
- Android画图之Matrix
- Android画图之Matrix
- Android画图之Matrix
- 【Android】画图之Matrix
- Android画图之Matrix
- android&&ScaleType
- pragma详解
- url地址静态化
- 如何调用MFC dll 来显示其中的对话框
- (2011.12.01)未有答案:接下来如何写博客呢?
- Android画图之Matrix(一)
- 【编程语言】java--集合
- Ubuntu系统启动过程详解
- 又发现amfext的几处内存泄漏的bug
- VS2008 代码对齐
- 人生如棋
- HTML4与HTML5之间的10个本质区别
- 备忘:让tomcat以非root身份运行
- uninitialized constant MysqlCompat::MysqlRes错误