[英]What's wrong with this Java code for Android?
我已经编写了这段代码将一个图像分成9个部分,这给了我运行时错误。 LogCat中没有错误,我被卡住了。 错误出现在底部的第7行(Bitmap.createBitmap(...);)。
public Bitmap[] getPieces(Bitmap bmp) {
Bitmap[] bmps = new Bitmap[9];
int width = bmp.getWidth();
int height = bmp.getHeight();
int rows = 3;
int cols = 3;
int cellHeight = height / rows;
int cellWidth = width / cols;
int piece = 0;
for (int x = 0; x <= width; x += cellWidth) {
for (int y = 0; y <= height; y += cellHeight) {
Bitmap b = Bitmap.createBitmap(bmp, x, y, cellWidth,
cellHeight, null, false);
bmps[piece] = b;
piece++;
}
}
return bmps;
}
这是android框架的局限性,无法提供适当的错误消息。 理想的解决方案是将代码包装在try / catch块中,并记录异常以控制台并相应地修复代码,但仅将其用于调试目的。
try {
// Code
}
catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE:"+e.toString());
}
上面的代码是从这里提取的:
代替
for (int x = 0; x <= width; x += cellWidth) {
for (int y = 0; y <= height; y += cellHeight) {
采用
for (int x = 0; x+cellWidth < width; x += cellWidth) {
for (int y = 0; y+cellHeight < height; y += cellHeight) {
以避免获取(至少部分)不存在的图像部分。
在您的代码中,段可以大于8,因此您在bmp上超出了索引范围。 您需要重写它,以便最右边和最下面的部分具有所有多余的部分,并且不一定相同。
或者,如果您需要它们具有相同的大小,请删除多余的行/列。 为了确保,我会像这样制定我的for循环
for (int cellX = 0; cellX < 3; cellX++) {
int x = cellX * cellWidth;
for (int cellY = 0; cellY < 3; cellY++) {
int y = cellY * cellHeight;
// find the cellWidth/Height that doesn't overflow the original image
Bitmap b = // get the bitmap
bmps[piece] = b;
piece++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.