颜色矩阵的第五列表示各个颜色的偏移量。
下面了解下ColorMatrix的常用API:
public void set(float[] src) 将src数组的值赋给颜色矩阵A
public final float[] getArray() 返回颜色矩阵A的具体数值,以一阶数组形式表示
public void setConcat(ColorMatrix matA,ColorMatrix matB) 将颜色矩阵matA和matB复合,相当与对图片进行matA矩阵处理再进行矩阵matB处理。
public void
postConcat
(ColorMatrix postmatrix) 若matA.postConcat(postmatrix)等价与 setConcat(postmatrix,matA)。
public void preConcat (ColorMatrix prematrix) 若matA.preConcat(prematrix)等价与 setConcat(matA,prematrix)。
public void
setRotate
(int axis, float degrees) 设置颜色分量旋转:axis==0旋转红色;axis==1对应绿色;axis==2对应蓝色,
源码如下:
/**
* Set the rotation on a color axis by the specified values.
* axis=0 correspond to a rotation around the RED color
* axis=1 correspond to a rotation around the GREEN color
* axis=2 correspond to a rotation around the BLUE color
*/
public void setRotate(int axis, float degrees) {
reset();
float radians = degrees * (float)Math.PI / 180;
float cosine = FloatMath.cos(radians);
float sine = FloatMath.sin(radians);
switch (axis) {
// Rotation around the red color
case 0:
mArray[6] = mArray[12] = cosine;
mArray[7] = sine;
mArray[11] = -sine;
break;
// Rotation around the green color
case 1:
mArray[0] = mArray[12] = cosine;
mArray[2] = -sine;
mArray[10] = sine;
break;
// Rotation around the blue color
case 2:
mArray[0] = mArray[6] = cosine;
mArray[1] = sine;
mArray[5] = -sine;
break;
default:
throw new RuntimeException();
}
}
public void
setSaturation
(float sat) 通过改变矩阵的值设置图像的饱和度 参数0对应灰色图像,1对应没改变
public void
setScale
(float rScale, float gScale, float bScale, float aScale) 设置矩阵的R,G,B,A等变量到对应的倍数。
对应的api为setScale(1,2,1,1);这个函数实际对应设置的是颜色矩阵对角线上的值。
下面的例子作出了对图像的一些处理,比较简单:
private void useColorMatrix(Canvas canvas,Paint paint) {
// TODO Auto-generated method stub
//清除画笔的颜色过滤
paint.setColorFilter(null);
cmatrix = new ColorMatrix();
cmatrix.set(carrycolor);
// cmatrix.reset();
// cmatrix.setSaturation(0F);
// cmatrix.setRotate(0, 100);
// cmatrix.setScale(2, 2, 2, 2);
//设置颜色矩阵过滤器
paint.setColorFilter(new ColorMatrixColorFilter(cmatrix));
canvas.drawBitmap(bitmap, 0,0, paint);
}
二、Matrix类详解
Matrix类是一个3x3的位置坐标矩阵,该类对矩阵进行初始化必须通过reset函数或者set...等方法,
图形的放大缩小,移动,旋转,透视,扭曲这些效果都可以用该此矩阵来完成。位置矩阵A的第一行控制X坐标,第二行控制y坐标第三行控制Z坐标。
这个矩阵的作用是对坐标x,y进行变换计算结果如下:
x'=a*x+b*y+c
y'=d*x+e*y+f
这个矩阵的作用是对坐标x,y进行变换计算结果如下:
x'=a*x+b*y+c
y'=d*x+e*y+f
由上面的公式可以看出c,f分别控制x,和y位置的偏移量,a和e控制X,与y坐标倍数的变化,所以
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = mPaint;
// useColorMatrix(canvas,paint);
matrix = new Matrix();
matrix.setValues(carrypos);
paint.setColorFilter(null);
canvas.drawBitmap(bitmap,matrix,paint); // you can setColorFilter(null);
carrypos[5] = 2*bitmap.getHeight(); //设置y坐标移动
carrypos[4] = -1; //设置绕x轴转180度
matrix.setValues(carrypos);
canvas.drawBitmap(bitmap, matrix, paint);
}
private float[] carrypos2 ={1,0,100,
0,1,100,
0,0,1}; //z no change
float[] test01 = carrypos2;
test01[1] = 0.5F;
matrix.setValues(test01);
canvas.drawBitmap(bitmap, matrix, paint);