一起学android之利用ColorMatrix进行图片的各种特效处理(32)

来源:互联网 发布:mysql dns 热切 编辑:程序博客网 时间:2024/05/18 03:50

原图:效果1:效果2:


效果3:效果4:




查看官方的API,其中ColorMatrix的说明如下:

5x4 matrix for transforming the color+alpha components of a Bitmap. The matrix is stored in a single array, and its 

treated as follows: [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t ] When applied to a color [r, g, b, a], the resulting 

color is computed as (after clamping) R' = a*R + b*G + c*B + d*A + e; G' = f*R + g*G + h*B + i*A + j; B' = k*R + l*G + 

m*B + n*A + o; A' = p*R + q*G + r*B + s*A + t;


那这里我简单的理解为:

所谓的颜色矩阵其实就是一张位图,那这个位图是5*4的矩阵,这个矩阵涉及到颜色和透明度,按照以上的一个公式,我们可以将这个颜色矩阵绘制出来:

   a   b   c    d   e

   f    g   h    i    j

   k    l   m   n   o

   p    q   r   s    i


除了5*4的颜色矩阵外,我们还需要图像的RGBA的值,通过RGBA可以决定图片颜色所呈现的效果,图像的RGBA的值存储在一个5*1的颜色分量矩阵中,如下:

 R

 G

 B

 A

 1


如果我们要改变图像的颜色,可以通过改变图像的颜色分量矩阵就可以做到,关于颜色分量矩阵的计算公式如下:


   a   b   c    d   e         R         aR+bG+cB+dA+e

   f    g   h    i    j          G          fR+gG+hB+jA+j

                                *  B  =

   k    l   m   n   o          A         kR+IG+mB+nA+o

   p    q   r   s    i           1         pR+qG+rB+sA+i


因此以上第一行代表红色成分,第二行代表绿色成分,第三行代表蓝色成分,第四行代表透明度。


代码如下:

public class MainActivity extends Activity {private Button btn_start;private ImageView img;private Bitmap bitmap;private float[] colorArray = {  1, 0, 0, 0, 0,0, 1, 0, 0, 1,2, 0, 1, 0, 0,0, 0, 0, 1, 0 };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.image_layout);initView();}private void initView() {img = (ImageView) findViewById(R.id.iv_image);bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();btn_start = (Button) findViewById(R.id.btn_start);btn_start.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Bitmap bm = ImageTools.toProcessImage(bitmap,colorArray);img.setImageBitmap(bm);}});}}

ImageTools工具类:

/** * 图片特效处理 * @param bmp  传入的图片 * @param colorArray 颜色矩阵值  * @return */public static Bitmap toProcessImage(Bitmap bmp,float[] colorArray){if(bmp!=null&&colorArray!=null){int width, height;height = bmp.getHeight();width = bmp.getWidth();Bitmap bm = Bitmap.createBitmap(width, height,Bitmap.Config.RGB_565);Paint myPaint = new Paint(); Canvas canvas=new Canvas(bm);                       ColorMatrix myColorMatrix = new ColorMatrix();         myColorMatrix.set(colorArray);        myPaint.setColorFilter(new ColorMatrixColorFilter(myColorMatrix));             canvas.drawBitmap(bmp,0,0,myPaint);          return bm;}else{return bmp;}}




转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/45193115 情绪控_



0 0