判断图片是浅色还是深色
首先需要获取
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;
}