捕捉“RuntimeException:Canvas:试图绘制太大......"

catch quot;RuntimeException: Canvas: trying to draw too large...quot;(捕捉“RuntimeException:Canvas:试图绘制太大......)

本文介绍了捕捉“RuntimeException:Canvas:试图绘制太大......"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序可以从文件系统中将图像绘制到屏幕上,如下所示:

I have an application which draws an image from the file system to screen like so:

Bitmap image = BitmapFactory.decodeFile(file.getPath());
imageView.setImageBitmap(image);

如果图像非常大,我会看到此错误:

If the image is very large I see this error:

java.lang.RuntimeException: Canvas: trying to draw too large(213828900bytes) bitmap.
    at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
    at android.graphics.Canvas.drawBitmap(Canvas.java:1415)
    ...

堆栈没有到达我的代码.我怎样才能捕捉到这个错误?还是有更合适的方法将图像绘制到 imageView 可以避免此错误?

The stack does not reach my code. How can I catch this error? Or is there a more appropriate way to be drawing the image to the imageView that can avoid this error?

推荐答案

Bitmap过大,Bitmap对象无法处理.因此,ImageView 应该有同样的问题.解决方法:在paint.net等程序中调整图像大小,或者为位图设置固定大小并进行缩放.

The Bitmap is too large in size and the Bitmap object cannot handle it. Thus, ImageView should have the same problem. Solution: resize the image either in programs such as paint.net, or set a fixed size for the bitmap and scale it.

在我继续之前,您的堆栈跟踪链接到位图的绘制,而不是创建对象:

Before I go further, your stacktrace links to the drawing of the bitmap, not creating the object:

在 android.graphics.Canvas.drawBitmap(Canvas.java:1415)

at android.graphics.Canvas.drawBitmap(Canvas.java:1415)

因此,您可以这样做:

Bitmap image = BitmapFactory.decodeFile(file.getPath());//loading the large bitmap is fine. 
int w = image.getWidth();//get width
int h = image.getHeight();//get height
int aspRat = w / h;//get aspect ratio
int W = [handle width management here...];//do whatever you want with width. Fixed, screen size, anything
int H = W * aspRat;//set the height based on width and aspect ratio

Bitmap b = Bitmap.createScaledBitmap(image, W, H, false);//scale the bitmap
imageView.setImageBitmap(b);//set the image view
image = null;//save memory on the bitmap called 'image'

或者,正如这里提到的,您可以使用毕加索 以及

Or, as mentioned here, you can use Picasso as well

注意

堆栈跟踪来自时您尝试加载的图像是 213828900 字节,即 213mb.这可能是一个分辨率非常高的图像,因为它们的尺寸越大,它们的字节数就越大.

The image you attempted to load in when the stacktrace is from, is 213828900 bytes, which is 213mb. This is probably an image with very high resolution, as the bigger in size they are, the bigger in bytes they are.

对于这么大的图像,缩放方法可能不起作用,因为它牺牲了太多质量.对于这么大的图片,Picasso 或 Glide 可能是加载图片而不会损失太大分辨率的唯一选项.

With images that big, the method with scaling may not work as it sacrifices too much of the quality. With images that big, Picasso or Glide may be the only options that loads in the pictures without a too big loss of resolution.

这篇关于捕捉“RuntimeException:Canvas:试图绘制太大......"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:捕捉“RuntimeException:Canvas:试图绘制太大......"

基础教程推荐