我有一个关于android中位图的问题:我有一个白边(大小未知)的位图。是否可以创建一个删除所有白边的新位图(矩形)?
Bitmap bmp = Bitmap.createBitmap(width, bmpheigth, Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.setBitmap(bmp);
canvas.drawColor(Color.WHITE);
// draw here things!
它被认为是未知的东西画在哪里。
做那件事的好方法是什么?
谢谢!
最佳答案
谢谢@maxim efimov和@stackoverflowexception
以防有人需要这类问题的片段:
此方法返回一个删除边距的剪切小位图。首先将像素传递给int数组,然后使用该数组比bitmap.getPixel方法快一点。
只需调用指示源位图和背景色的方法。
Bitmap bmp2 = removeMargins(bmp, Color.WHITE);
private static Bitmap removeMargins2(Bitmap bmp, int color) {
// TODO Auto-generated method stub
long dtMili = System.currentTimeMillis();
int MTop = 0, MBot = 0, MLeft = 0, MRight = 0;
boolean found1 = false, found2 = false;
int[] bmpIn = new int[bmp.getWidth() * bmp.getHeight()];
int[][] bmpInt = new int[bmp.getWidth()][bmp.getHeight()];
bmp.getPixels(bmpIn, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),
bmp.getHeight());
for (int ii = 0, contX = 0, contY = 0; ii < bmpIn.length; ii++) {
bmpInt[contX][contY] = bmpIn[ii];
contX++;
if (contX >= bmp.getWidth()) {
contX = 0;
contY++;
if (contY >= bmp.getHeight()) {
break;
}
}
}
for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
// looking for MTop
for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MTop 2", "Pixel found @" + hP);
MTop = hP;
found2 = true;
break;
}
}
}
found2 = false;
for (int hP = bmpInt[0].length - 1; hP >= 0 && !found2; hP--) {
// looking for MBot
for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MBot 2", "Pixel found @" + hP);
MBot = bmp.getHeight() - hP;
found2 = true;
break;
}
}
}
found2 = false;
for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
// looking for MLeft
for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MLeft 2", "Pixel found @" + wP);
MLeft = wP;
found2 = true;
break;
}
}
}
found2 = false;
for (int wP = bmpInt.length - 1; wP >= 0 && !found2; wP--) {
// looking for MRight
for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MRight 2", "Pixel found @" + wP);
MRight = bmp.getWidth() - wP;
found2 = true;
break;
}
}
}
found2 = false;
int sizeY = bmp.getHeight() - MBot - MTop, sizeX = bmp.getWidth()
- MRight - MLeft;
Bitmap bmp2 = Bitmap.createBitmap(bmp, MLeft, MTop, sizeX, sizeY);
dtMili = (System.currentTimeMillis() - dtMili);
Log.e("Margin 2",
"Time needed " + dtMili + "mSec\nh:" + bmp.getWidth() + "w:"
+ bmp.getHeight() + "\narray x:" + bmpInt.length + "y:"
+ bmpInt[0].length);
return bmp2;
}