我们知道如下代码可以将图片按原比例整个绘制下来。
bmp.setPixels(newPx, 0, width, 0, 0, width, height);
但有的时候如果想单纯绘制出图片中的某一块,就像截图一样,该怎么做呢?
首先列出setPixels的参数信息:
-
setPixels
-
Added in API level
1
-
void setPixels (int[] pixels, // 设置像素数组,对应点的像素被放在数组中的对应位置,像素的argb值全包含在该位置中
-
int offset, // 设置偏移量,我们截图的位置就靠此参数的设置
-
int stride, // 设置一行打多少像素,通常一行设置为bitmap的宽度,
-
int x, // 设置开始绘图的x坐标
-
int y, // 设置开始绘图的y坐标
-
int width, // 设置绘制出图片的宽度
-
int height)
// 设置绘制出图片的高度
设置偏移量的时候,我们要清楚是针对像素的偏移量,而整张bitmap的像素的个数为width * height(矩形)。
如此可推断出:
我们如果想从左上角开始截图,偏移量可以设置为0。
当我们想从右上角开始截图的时候,偏移量可以设置为width / 2。
左边中间偏移量:width * height / 2。
右边中间偏移量:width * height /2 - width /2。
-
int color;
-
int r, g, b, a;
-
for (
int i =
0; i < width * height; i++) {
-
color = oldPx[i];
-
r = Color.red(color);
-
g = Color.green(color);
-
b = Color.blue(color);
-
a = Color.alpha(color);
-
-
...
-
}
经过个人多次尝试,得出如下易用结论:
右上角:
bmp.setPixels(newPx, width / 2, width, 0, height / 2, width / 2, height / 2);
左上角:
bmp.setPixels(newPx, 0, width, 0, height / 2, width / 2, height / 2);
右下角:
bmp.setPixels(newPx, width * height / 2, width, 0, height / 2, width / 2, height / 2);
左下角:
bmp.setPixels(newPx, width * height / 2 - width / 2, width, 0, height / 2, width / 2, height / 2);