有没有任何代码可以在android中设置壁纸而无需裁剪和缩放?

2024-06-20

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

    Bitmap bmd = BitmapFactory.decodeStream(is);

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

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

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


我迟到了回复这个。希望它对您和访问您问题的人有所帮助:

对于您的情况,请尝试通过如下方式将图片调整为设备大小:

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"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有任何代码可以在android中设置壁纸而无需裁剪和缩放? 的相关文章

随机推荐