矩阵有两种:一个是Matrix负责缩放、平移、旋转、错切,一个是ColorMatrix负责更改图片的argb
如果不进行设置默认原点都为控件的左上角
Matrix: [a,b,c,
d,e,f,
g,k,l]
解释:a,e代表缩放 b,d代表错切 c,f代表平移量,g,k不经常用 l代表整体的缩放(如果为2则变为原来的一半,如果为0.5则变为原来的2倍)
缩放
Matrix matrix = new Matrix(); matrix.setValues(new float[]{ 1,0,0, 0,.5f,0, 0,0,1 });也可以
Matrix matrix = new Matrix(); matrix.setScale(1,0.5f);//也可以设置原点matrix.setScale(1,0.5f,src.getWidth()/2,src.getHeight()/2);平移
Matrix matrix = new Matrix(); matrix.setValues(new float[]{ 1,0,100, 0,1,0, 0,0,1 });也可以
Matrix matrix = new Matrix(); matrix.postTranslate(src.getWidth(), 0);//向左平移图片的宽度
旋转
旋转的矩阵:【cos -sin 0
sin cos 0
0 0 1】
Matrix matrix = new Matrix(); matrix.setValues(new float[]{ 0,-1,0, -1,0,0, 0,0,1 });
也可以
Matrix matrix = new Matrix(); matrix.setRotate(90);
Matrix matrix = new Matrix(); matrix.setValues(new float[]{ 1,1,0, -1,1,0, 0,0,1 });也可以
Matrix matrix = new Matrix(); matrix.setSkew(-1f,1f);
举例:
private void mirrorImg() { Bitmap src = BitmapFactory.decodeResource(getResources(), R.mipmap.background); Matrix matrix = new Matrix(); matrix.preScale(-1, 1);//不进行缩放,如果不设置坐标原点则默认为(0,0),相对于控件的左上角 matrix.postTranslate(src.getWidth(), 0);//向左平移图片的宽度 Bitmap blankBitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig()); Canvas canvas = new Canvas(blankBitmap); canvas.drawBitmap(src, matrix, new Paint()); iv2.setImageBitmap(blankBitmap); }在这里涉及到setXXX , preXXX , postXXX的区别,setXXX方法会将之前设置pre、post方法刷除,pre为前乘,post为后乘
matrix.preScale(-1,1); matrix.preTranslate(250,50); //执行的顺序是:translate()->scale()
matrix.postScale(-1, 1); matrix.postTranslate(250, 50); //执行的顺序是:scale()->translate()以上结论是根据pre为前乘,post为后乘得出的
另外还有
matrix.preScale(-1,1); matrix.preTranslate(250,50); matrix.postScale(-1, 1); matrix.postTranslate(250, 50); matrix.setScale(1,1); matrix.postTranslate(100, 0); matrix.preTranslate(-50,0); //执行的顺序是:pretranslate(-50,0)->scale(1,1)->posttranslate(100)接下来就是ColorMatrix的应用, 的第一行参数abcde决定了图像的红色成分,第二行参数fghij决定了图像的绿色成分,第三行参数klmno决定了图像的蓝色成分,第四行参数pqrst决定了图像的透明度,第五列参数ejot是颜色的偏移量。
代码如下:
private void changeColorImg() { Bitmap src = BitmapFactory.decodeResource(getResources(), R.mipmap.han); ColorMatrix matrix = new ColorMatrix(); matrix.set(new float[]{ 1, 3, 0, 0, 0, 0, 1, 4, 0, 0, 0, 0, 1, 5, 0, 0, 0, 0, 1, 0 }); Bitmap blankBitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig()); Canvas canvas = new Canvas(blankBitmap); Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(matrix)); canvas.drawBitmap(src, new Matrix(), paint); iv2.setImageBitmap(blankBitmap); }