如何确定最大的稳定位图尺寸



我正在开发一个应用程序,允许用户在位图上的受限画布内绘制。每个绘图都在一个单独的位图上创建,然后在onDraw()方法中将其添加到主位图中。这个主位图需要比屏幕尺寸大,这样用户就有足够的空间来绘制详细的场景。因此,我还为用户提供了在主位图上平移/缩放的功能。

我注意到这个主位图大小会影响设备绘图能力的性能。在这一点上,尺寸被静态设置为3000X3000,对于我的Galaxy 10.1 Pro平板电脑来说效果很好,但在我的低端Galaxy手机上就非常不稳定了。这个应用程序不是为了在手机上使用,但问题仍然是一样的:我如何动态地确定主位图的尺寸,使性能在不同设备上保持一致?

如果您想查看屏幕大小,请执行此操作。文档在这里

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

然后你可以使用这些信息来调整图像的大小。

您可以设置. injustdecodebounds = true来获取图像大小而不加载图像。如果图像太大,可以调整它的大小。下面是示例代码。

private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();

int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
      IMAGE_MAX_SIZE) {
   scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", 
   orig-height: " + o.outHeight);
Bitmap b = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
    scale--;
    // scale to max possible inSampleSize that still yields an image
    // larger than target
    o = new BitmapFactory.Options();
    o.inSampleSize = scale;
    b = BitmapFactory.decodeStream(in, null, o);
    // resize to desired dimensions
    int height = b.getHeight();
    int width = b.getWidth();
    Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
       height: " + height);
    double y = Math.sqrt(IMAGE_MAX_SIZE
            / (((double) width) / height));
    double x = (y / height) * width;
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, 
       (int) y, true);
    b.recycle();
    b = scaledBitmap;
    System.gc();
} else {
    b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " + 
   b.getHeight());
return b;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}

最新更新