5

我正在创建一个画廊应用程序,我的第一个应用程序,这是我的代码

    Bitmap bmd = BitmapFactory.decodeStream(is);

    try{
        getApplicationContext().setWallpaper(bmd);
    }catch(IOException e){
        e.printStackTrace();
    }

上面的代码设置了壁纸但是设置后壁纸会被裁剪或缩放!我可以在上面的代码中做任何修改,以便我可以在设置壁纸时不缩放或裁剪!!!!

Lzzzz 帮帮我!!提前致谢 :-)

4

2 回答 2

4

我迟到了。希望它可以帮助您和那些访问您的问题的人:

在您的情况下,尝试通过以下方式将图片调整为设备大小:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width

// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options);

WallpaperManager wm = WallpaperManager.getInstance(this);
try {
    wm.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
    Log.e(TAG, "Cannot set image as wallpaper", e);
}

如果上面的代码不起作用,做一个小的修改:

...
WallpaperManager wm = WallpaperManager.getInstance(this);
try {
    wm.setBitmap(decodedSampleBitmap);
    wm.suggestDesiredDimensions(width, height);
} catch (IOException e) {
    Log.e(TAG, "Cannot set image as wallpaper", e);
}

和方法calculateInSampleSize

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

并记得添加权限:

<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
于 2014-02-05T12:33:52.743 回答
0

最简单的方法是将你的壁纸图片扩展为一个正方形,将你的内容放在新图片的中心。如果你的设备是 w1024 h600,你的壁纸应该是 1024 1024。如果你的设备是 w600 h1024,你的壁纸也应该是 1024*1024。

于 2021-04-14T06:41:14.950 回答