编辑:添加了 Y 偏移修复 - 感谢@Jason Goff!
好的,原来s3上主屏幕的最小宽度不是720,而是1280!您可以通过调用找出所需的墙纸的最小宽度和高度
wallpaperManager.getDesiredMinimumWidth();//returned 1280 on s3
wallpaperManager.getDesiredMinimumHeight();//also returned 1280 on s3
因此,为了将壁纸应用到屏幕中心,我必须动态创建一个 1280x1280 的空白位图,然后将我的壁纸覆盖到空白位图的中心,我创建了一个带有调整位图方法的静态 BitmapHelper 类,这里是创建位图和覆盖壁纸图像的方法:
public class BitmapHelper {
public static Bitmap overlayIntoCentre(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);//draw background bitmap
//overlay the second in the centre of the first
//(may experience issues if the first bitmap is smaller than the second, but then why would you want to overlay a bigger one over a smaller one?!)
//EDIT: added Y offest fix - thanks @Jason Goff!
canvas.drawBitmap(bmp2, (bmp1.getWidth()/2)-(bmp2.getWidth()/2), (bmp1.getHeight()/2)-(bmp2.getHeight/2), null);
return bmOverlay;
}
public static Bitmap createNewBitmap(int width, int height)
{
//create a blanks bitmap of the desired width/height
return Bitmap.createBitmap(width, height, Config.ARGB_8888);
}
}
并使用我的 BitmapHelper 继承我的其余代码:
private void applyWallpaperFromFile(final File file)
{
Bitmap wallpaperImage = BitmapFactory.decodeFile(file.getPath());
try {
if((wallpaperManager.getDesiredMinimumWidth()>0)&&(wallpaperManager.getDesiredMinimumHeight()>0))
{
Bitmap blank = BitmapHelper.createNewBitmap(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight());
Bitmap overlay = BitmapHelper.overlayIntoCentre(blank, wallpaperImage);
wallpaperManager.setBitmap(overlay);
}
else
{
wallpaperManager.setBitmap(wallpaperImage);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WallpaperActivity.this,"Wallpaper set to:"+file.getName(), Toast.LENGTH_SHORT).show();
}
});
}