天天看点

Android 图像绘制之Matrix 的使用

Android 中拥有众多的图像绘制的函数,而功能最强大的就是 drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)

Android官方文档的描述为Draw the bitmap using the specified matrix.翻译成中文就是:用特定的矩阵来画图。而在其中最重要的参数就是 matrix。

图片的平移:就是设定其中心位置的变换,我们可是使用这样的两个函数做到:

setTranslate(float dx, float dy)

postTranslate(float dx, float dy)

Android 图像绘制之Matrix 的使用

对于矩阵变换此处的前乘和后乘我们不做过多的介绍,我们按照一种固定的变化顺序来进行变化,故全部使用后乘来解决。即全为post开头的方法,而set开头的方法是对我们已经做过的变换进行重置。好吧,实例说明一切:

                    matrix.setTranslate(100, 100);

                    canvas.drawBitmap(bitmap,matrix,mPaint);

Android 图像绘制之Matrix 的使用

图片的旋转:同样的四个函数:

postRotate(float degrees)

postRotate(float degrees, float px, float py)

setRotate(float degrees)

setRotate(float degrees, float px, float py)

其中的px、py是代表旋转的中心点的意思,如果不指定中心点的话,默认是(0,0)点进行旋转。

              matrix.setTranslate(100, 100);

                matrix.postRotate(90,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                canvas.drawBitmap(bitmap,matrix,mPaint);

Android 图像绘制之Matrix 的使用

图片的缩放:

postScale(float sx, float sy)

postScale(float sx, float sy, float px, float py)

setScale(float sx, float sy, float px, float py)

setScale(float sx, float sy)

其中的参数的情况与图片旋转的情况一样,上实例:

                  matrix.setTranslate(100, 100);

                  matrix.postRotate(90,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  matrix.postScale(2,2,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  canvas.drawBitmap(bitmap,matrix,mPaint);

Android 图像绘制之Matrix 的使用

图片的反转:这个情况android的API里面没有给我们直接写出,但是我们可以使用图片缩放的函数来实现。看实例吧:

                  matrix.setTranslate(100, 100);

                  matrix.postRotate(90,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  matrix.postScale(2,2,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  matrix.postScale(-1f,-1f,100+bitmap.getWidth()/2,100+bitmap.getHeight()/2);

                  canvas.drawBitmap(bitmap,matrix,mPaint);

Android 图像绘制之Matrix 的使用

基本上通过如上的变换就可以画出想要的图像了。