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

Android 實用工具函式收集:螢幕密度、版本號與圖片倒影

編輯:關於 Android 程式設計

日常開發中反覆用到的一些小函式,累積起來就是一個好用的工具類。以下幾個是比較常被翻出來的。

1. 取得螢幕密度(用於螢幕適配)

public static float getDensity(Context ctx) {
    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    return metrics.density;
}

density 是 dp 與 px 的換算係數。已知這個值,就能把設計稿上的 dp 換成實際像素:px = dp * density。

2. 取得版本名稱

public static String getVersionName(Context context, String packageName) {
    try {
        PackageInfo pInfo = context.getPackageManager()
                .getPackageInfo(packageName, PackageManager.GET_META_DATA);
        return pInfo.versionName;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

要拿自己的版本號,可以直接用 context.getPackageName() 當參數,或者更簡潔地讀 BuildConfig.VERSION_NAME(編譯期就決定,不必查 PackageManager)。

3. 生成帶漸變效果的圖片倒影

public static Bitmap createMirro(Bitmap srcbitmap) {
    int width = srcbitmap.getWidth();
    int height = srcbitmap.getHeight();
    int shadow_height = 15;
    int[] pixels = new int[width * height];
    srcbitmap.getPixels(pixels, 0, width, 0, 0, width, height);

    // 陰影效果:逐行遞增 alpha,越往下越不透明
    int alpha = 0x00000000;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int index = y * width + x;
            int r = (pixels[index] >> 16) & 0xff;
            int g = (pixels[index] >> 8) & 0xff;
            int b = pixels[index] & 0xff;
            pixels[index] = alpha | (r << 16) | (g << 8) | b;
        }
        if (y >= (height - shadow_height)) {
            alpha = alpha + 0x1F000000;
        }
    }

    // 垂直翻轉
    Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    for (int y = 0; y < height; y++) {
        bm.setPixels(pixels, y * width, width, 0, height - y - 1, width, 1);
    }
    return Bitmap.createBitmap(bm, 0, 0, width, shadow_height);
}

原理是兩段處理:先把原圖每個像素的 alpha 通道依行號遞減,做出漸層淡出;再用 setPixels 把每一行寫到「垂直鏡像位置」(height - y - 1),完成翻轉;最後裁出底部一小塊當作倒影。

效能上的提醒

這個倒影函式是雙層迴圈逐像素運算,在解析度高的圖片上會相當吃 CPU,而且產生的 Bitmap 物件沒有 recycle。若要在清單捲動中使用,建議:

  • 先把原圖縮圖到實際顯示尺寸再處理,不要拿 2000px 的原圖去算;
  • 改用 Matrix 的 setScale(1, -1) 搭配 LinearGradient 做遮罩,交給 GPU 處理,速度差很多;
  • 或者直接宣告一個自訂 View,在 onDraw() 中即時繪製,不必產生額外 Bitmap。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved