`
zhy20045923
  • 浏览: 153373 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

判断图片是浅色还是深色

 
阅读更多
首先需要获取

WallpaperManager.FLAG_LOCK
代表锁屏壁纸

WallpaperManager.FLAG_SYSTEM
代表系统壁纸,桌面壁纸

如果

fd = null
说明锁屏壁纸和桌面壁纸是同一个



public static boolean isLockWpLight(Context context) {
    Palette p = getStatusBarPalette(context);
    if(null == p) {
return false;
}
return !isLegibleOnWallpaper(Color.WHITE, p.getSwatches());
}

private static Palette getStatusBarPalette(Context context) {
    WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
    int statusBarHeight = context.getResources ().getDimensionPixelSize (R.dimen.status_bar_height);
    try (ParcelFileDescriptor fd = wallpaperManager
            .getWallpaperFile(WallpaperManager.FLAG_LOCK)) {
        BitmapRegionDecoder decoder = BitmapRegionDecoder
                .newInstance(fd.getFileDescriptor(), false);
Rect decodeRegion = new Rect(0, 0,
decoder.getWidth(), statusBarHeight);
Bitmap bitmap = decoder.decodeRegion(decodeRegion, null);
decoder.recycle();
        if (bitmap != null) {
return Palette.from(bitmap).clearFilters().generate();
}
    } catch (IOException | NullPointerException e) {
        Log.e(TAG, "Fetching partial bitmap failed, trying old method", e);
}
    Bitmap wallpaper = ((BitmapDrawable) wallpaperManager.getDrawable()).getBitmap();
    return Palette.from(wallpaper)
            .setRegion(0, 0, wallpaper.getWidth(), statusBarHeight)
            .clearFilters()
            .generate();
}

private static boolean isLegibleOnWallpaper(int color, List<Palette.Swatch> wallpaperSwatches) {
int legiblePopulation = 0;
    int illegiblePopulation = 0;
    for (Palette.Swatch swatch : wallpaperSwatches) {
if (isLegible(color, swatch.getRgb())) {
            legiblePopulation += swatch.getPopulation();
} else {
            illegiblePopulation += swatch.getPopulation();
}
    }
return legiblePopulation > illegiblePopulation;
}

private static boolean isLegible(int foreground, int background) {
    background = ColorUtils.setAlphaComponent(background, 255);
    return ColorUtils.calculateContrast(foreground, background) >= 2;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics