Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 藍牙打印踩坑記:解析 resizeImage 位圖縮放報錯問題

編輯:關於 Android 程式設計

最近用網路上找到的 gprinter.jar 做藍牙與收銀機的對接打印,結果一跑就拋出這樣的錯誤:

x + width must be <= bitmap.width()

一整排類似錯誤,追根溯源都指向了同一處——矩陣的邊界檢測:

/**
 * Shared code to check for illegal arguments passed to getPixels() or setPixels()
 */
private void checkPixelsAccess(int x, int y, int width, int height, int offset, int stride, int pixels[]) {
    checkXYSign(x, y);
    if (width < 0) {
        throw new IllegalArgumentException("width must be >= 0");
    }
    if (height < 0) {
        throw new IllegalArgumentException("height must be >= 0");
    }
    if (x + width > getWidth()) {
        throw new IllegalArgumentException("x + width must be <= bitmap.width()");
    }
    if (y + height > getHeight()) {
        throw new IllegalArgumentException("y + height must be <= bitmap.height()");
    }
    ...
}

翻來覆去研究了半天源碼,才發現問題出在 resizeImage(mBitmap, width, height) 這個方法的呼叫上。原始方法長這樣:

public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
    Bitmap BitmapOrg = bitmap;
    int width = BitmapOrg.getWidth();
    int height = BitmapOrg.getHeight();
    int newWidth = w;
    int newHeight = h;
    float scaleWidth = newWidth / width;
    float scaleHeight = newHeight / height;
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true);
    return resizedBitmap;
}

真正的病根在這兩行:float scaleWidth = newWidth / width;。這裡是 int / int 的整數除法,先做完除法再轉 float,結果往往被截斷成 0 或極小的值,導致後續 createBitmap 計算出的尺寸越界,於是便拋出了那個惱人的 x + width must be <= bitmap.width()。

解決辦法很簡單,把運算順序調整一下,讓其中一個操作數先變成浮點數:float = int * 1.0f / int,這樣就不會再報錯了。這個坑在平板上尤其容易踩到,改完之後藍牙打印一切正常。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved