这段时间项目有需求要获取桌面的壁纸来设成背景,发现网上很多同学都通过WallpaperManager的getDrawable等API来获取,这样的确能获得到壁纸,但是要稍微注意一下。
桌面的壁纸可是很大很大的一张哦,你要直接用来设置成背景,那可是很丑的。所以我们需要稍微处理一下。
大致思路就是把一张壁纸切成几片,当前屏幕对应那片,我们就要那片。上个图:
// 获取壁纸管理器
WallpaperManager wallpaperManager = WallpaperManager
.getInstance(mContext);
// 获取当前壁纸
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
// 将Drawable,转成Bitmap
Bitmap bm = ((BitmapDrawable) wallpaperDrawable).getBitmap();
// 需要详细说明一下,mScreenCount、getCurrentWorkspaceScreen()、mScreenWidth、mScreenHeight分别
//对应于Launcher中的桌面屏幕总数、当前屏幕下标、屏幕宽度、屏幕高度.等下拿Demo的哥们稍微要注意一下
float step = 0;
// 计算出屏幕的偏移量
step = (bm.getWidth() - LauncherPreferenceModel.mScreenWidth)
/ (LauncherPreferenceModel.mScreenCount - 1);
// 截取相应屏幕的Bitmap
Bitmap pbm = Bitmap.createBitmap(bm, (int) (mLauncher
.getCurrentWorkspaceScreen() * step), 0,
(int) (LauncherPreferenceModel.mScreenWidth),
(int) (LauncherPreferenceModel.mScreenHeight));
// 设置 背景
layout.setBackgroundDrawable(new BitmapDrawable(pbm));
本文介绍了一种方法,通过使用WallpaperManager API获取桌面壁纸,并将其切分为多部分,以便根据不同屏幕大小设置合适的背景。这种方法涉及到将大尺寸的壁纸转换为多个较小的Bitmap,以匹配当前屏幕的需求,从而实现美观且高效的背景设置。
5230

被折叠的 条评论
为什么被折叠?



