2017-02-27 25 views
-1

我有一個應用程序,它從文件系統繪製圖像到屏幕,像這樣:抓「的RuntimeException:畫布:企圖拉攏過大......」

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

如果圖像是非常大的我見此錯誤:

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可以避免此錯誤?

回答

0

位圖的尺寸過大和位圖對象不能處理它。因此,ImageView應該有同樣的問題。解決方案:在諸如paint.net之類的程序中調整圖像大小,或者爲位圖設置固定大小並對其進行縮放。

我走得更遠之前,你的堆棧跟蹤鏈接位圖的繪製,而不是創建該對象:

因此,你可以這樣做:

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' 

或者,如mentioned here,您還可以使用Picasso以及

備註

您在堆棧跟蹤時嘗試加載的映像是213828900 bytes,它是213mb。這可能是分辨率非常高的圖像,因爲它們的大小越大,它們的字節越大。

如果圖像很大,縮放的方法可能無法正常工作,因爲它會犧牲太多的質量。隨着圖像的大,畢加索可能是唯一加載它的東西,而不會有太大的分辨率損失。

+0

它不保留寬高比,我們不知道原始位圖的大小是多少。 –

+0

編輯反思 – Zoe

0

我修復了LunarWatcher代碼中的錯誤。

Bitmap image = BitmapFactory.decodeFile(file.getPath()); 
float w = image.getWidth();//get width 
float h = image.getHeight();//get height 
int W = [handle width management here...]; 
int H = (int) ((h*W)/w); 
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'