参考《Android群英传》6.6
一、改变色光属性
Android系统中封装了ColorMatrix类,就是颜色矩阵,通过这个类可以很方便的改变矩阵值来处理颜色效果。创建一个ColorMatrix和创建普通类是一样的。
ColorMatrix中改变色光属性的几个方法:
setRotate(axis, degrees):设置颜色的色调。
第一个参数:系统分别用了0,1,2代表Red,Green,Blue三种颜色的处理。
第二个参数:需要处理的值。
ColorMatrix hueMatrix = new ColorMatrix();
hueMatrix.setRotate(0, hue);
hueMatrix.setRotate(1, hue);
hueMatrix.setRotate(2, hue);
setSaturation(saturation):设置颜色的饱和度。参数就是颜色饱和度的值,饱和度为0时,图像就成灰度图像了。
ColorMatrix saturationMatrix = new ColorMatrix();
saturationMatrix.setSaturation(saturation);
setScale(rScale, gScale, bScale, aScale):设置图像亮度,当三原色以相同比例混合时,就会显示出白色,当亮度为0时,图像就全黑了。
ColorMatrix lumMatrix = new ColorMatrix();
lumMatrix.setScale(lum, hue, saturation, 1);
postConcat(hueMatrix):将以上三种方式处理的效果叠加起来显示混合效果。
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.postConcat(hueMatrix);
colorMatrix.postConcat(saturationMatrix);
colorMatrix.postConcat(lumMatrix);
实例代码:
package com.example.androidcolormatrix;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class SeekBarActivity extends Activity implements OnSeekBarChangeListener {
private ImageView imageView;
private Bitmap bitmap;
private SeekBar seekbarHue,seekbarSaturation,seekbarLum;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化组件
imageView = (ImageView) findViewById(R.id.imageView);
seekbarHue = (SeekBar) findViewById(R.id.seekbarHue);
seekbarSaturation = (SeekBar) findViewById(R.id.seekbarSaturation);
seekbarLum = (SeekBar) findViewById(R.id.seekbarLum);
//给拖动条设置初值
seekbarHue.setProgress(50);
seekbarSaturation.setProgress(50);
seekbarLum.setProgress(50);
//给imageview添加位图
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.we);
imageView.setImageBitmap(bitmap);
//给拖动条添加监听
seekbarHue.setOnSeekBarChangeListener(this);
seekbarSaturation.setOnSeekBarChangeListener(this);
seekbarLum.setOnSeekBarChangeListener(this);
}
//设置ColorMatrix返回设置之后的位图
private Bitmap handleImage(Bitmap bm, float hue, float saturation, float lum){
Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
ColorMatrix hueMatrix = new ColorMatrix();
hueMatrix.setRotate(0, hue);
hueMatrix.setRotate(1, hue);
hueMatrix.setRotate(2, hue);
ColorMatrix saturationMatrix = new ColorMatrix();
saturationMatrix.setSaturation(saturation);
ColorMatrix lumMatrix = new ColorMatrix();
lumMatrix.setScale(lum, hue, saturation, 1);