Android使用Bitmap表示位图,而位图是由像素点组成的,每一个像素点都有具体的ARGB值,通过改变像素的的ARGB值可以实现图片的各种效果,Bitmap的getPixels()方法用于提取整个Bitmap中的像素点, 并保存到一个数组中,该方法如下:
getPixels( int[] pixels, int offset, int stride, int x, int y, int width, int height)
- pixels 接收位图颜色值的数组
- offset 写入到pixels[]中的第一个像素索引值
- stride pixels[]中的行间距
- x 从位图中读取的第一个像素的x坐标值
- y 从位图中读取的第一个像素的y坐标值
- width 从每一行中读取的像素宽度
- height 读取的行数
通常情况下使用如下方式获取像素值:
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
下面是一个使用变换像素点的ARGB值来实现的底片效果:
mBitmap = BitmapFactory.decodeFile(uri.getPath());
mDesBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), mBitmap.getConfig());
setBitmapPixels(mBitmap, mDesBitmap);
mImageView.setImageBitmap(mDesBitmap);
private void setBitmapPixels(Bitmap bitmap, Bitmap desBitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
int length = pixels.length;
int color;
int r, g, b, a;
for (int i = 0; i < length; i++) {
color = pixels[i];
r = Color.red(color);
g = Color.green(color);
b = Color.blue(color);
a = Color.alpha(color);
r = 255 - r;
g = 255 - g;
b = 255 - b;
r = r > 255 ? 255 : r < 0 ? 0 : r;
g = g > 255 ? 255 : g < 0 ? 0 : g;
b = b > 255 ? 255 : b < 0 ? 0 : b;
a = a > 255 ? 255 : a < 0 ? 0 : a;
pixels[i] = Color.argb(a, r, g, b);
}
desBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
}
效果如下: