这篇博客中不论是通过ColorMatrix处理图像还是要实现图像的底片效果、老照片效果和浮雕效果都是通过像素法(Pixel)进行改变的。
一、Matrix与ColorMatrix的区别
1.Matrix.
Matrix类是以9个float型数字的一维数组表示的。每个数字都对应于图像上每个点的3个坐标(x,y或z)之一。
Matirx可以在当前位图对象上进行绘制或从另一个位图对象创建某个位图对象时,可以使用该类。这个类可以让我们对位图进行旋转、裁剪、缩放、平移等操作。
2、ColorMatrix
ColorMatrix也是一个浮点数数组,可以对图像的像素进行操作。然后不同于操作x, y和z坐标,它操作的是颜色值——每个像素的RGBA值。
ColorMatrix通过Canvas在Bitmap上进行绘制,通过Paint对象设置ColorMatrix在进行绘制。
二、ColorMatrix的原理与使用
1、ColorMatrix处理图片原理
ColorMatrix正如我们所翻译的“颜色矩阵”,它是通过矩阵的方式作用与图像的像素来实现的图片的处理。
(1)ColorMAtrix颜色矩阵
颜色矩阵M是一个5*4的矩阵,如图所示。但是在Android中,颜色矩阵M是以一维数组M=[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t]的方式进行存储的。
(2)颜色的分量矩阵
颜色的分量矩阵分别有R、G、B、A、1组成,用于调整三原色和透明度
(3)变换过程
第一行将会影响红色,第二行影响绿色,第三行影响蓝色,最后一行操作的是Alpha值。
ps:默认的ColorMatrix如下面所示,它是不会改变图像的。
1,0,0,0,0
0,1,0,0,0
0,0,1,0,0
0,0,0,1,0
2、ColorMatrix的使用
ColorMatrix cm = new ColorMatrix();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
Canvas canvas=new Canvas(bimap_new); canvas.drawBitmap(bitmap,0,0,paint);
//在bitmap_new上面进行绘制
三、ColorMatrix实例
实现效果如上图所示。
1、布局(布局中使用GridLayout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="15dp"
android:layout_weight="2"/>
<GridLayout
android:id="@+id/gridlayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:rowCount="4"
android:columnCount="5"
android:layout_weight="3">
</GridLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_reset"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="复位"/>
<Button
android:id="@+id/btn_change"
android:layout_width="0dp"
android:layout_weight="1"
a