Is there any code to set wallpaper without cropping and zooming in android?

十年热恋 提交于 2019-12-05 11:00:16

I am late to reply this. Hope it helps you and those who visits your question:

In your case, try to adjust your picture to device size by somewhat like this:

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);
}

If above code doesn't work, do a small modification:

...
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);
}

And the method 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;
}

and remember to add permissions:

<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!