第一次寫博客,都是低級的錯誤,大神見笑了。
今天做安卓加載圖片到 ImageView,報了 一個 java.lang.IllegalArgumentException: width and height must be > 0錯誤,只能怪我英文不好,沒看懂。先把我的代碼貼出來。
1 bmp = BitmapFactory.decodeStream(cr.openInputStream(uri)); 2 3 // 縮放圖片 4 WindowManager wm = getWindowManager(); 5 int width = wm.getDefaultDisplay().getWidth(); 6 int height = wm.getDefaultDisplay().getHeight(); 7 // 圖片的寬高 8 int photo_width = bmp.getWidth(); 9 int photo_height = bmp.getHeight(); 10 // 縮放比例,如小於1就設置為1 11 int bili = (photo_width/width)>(photo_height/height)?(photo_width/width):(photo_height/height); 12 bili = bili>1?bili:1; 13 System.out.println("bili:"+bili); 14 Matrix matrix = new Matrix(); 15 matrix.postScale(1/bili,1/bili); //長和寬放大縮小的比例 16 Bitmap resizeBmp = Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true); 17 18 System.out.println(resizeBmp.getWidth()+":"+resizeBmp.getHeight()); 19 20 img1.setImageBitmap(resizeBmp);
一直在15行報錯,我就不明白了,最后百度 matrix.postScale 中出現了賦值,於是我恍然大悟, matrix.postScale 接收的浮點類型的數,而我給的整數類型, 於是我該成了 matrix.postScale(1f/bili,1f/bili); 就沒報錯了。后來我仔細想想,這里的計算不合理,前面計算比例的時候應該用float的。
以后還是要養成好習慣,浮點類型的盡量寫上 f。