Android WallpaperManager crops image

本文介绍了一种确保壁纸图片能够正确填充整个屏幕的方法。通过自动为壁纸图片添加填充,使其大小与屏幕分辨率相匹配,避免了图片显示不全的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I had the same problem. I made an image that is the size of the screen and adding padding to the image so that it is as large as the WallpaperManager getDesiredMinimumWidth() and getDesiredMinimumHeight().

It seemed better to have some code automatically add the padding so that is what I used below. Make sure the image is the same size as the screen.

private void setWallpaper() {
    try {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        //import non-scaled bitmap wallpaper
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap wallpaper = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper, options);

        if (wallpaperManager.getDesiredMinimumWidth() > wallpaper.getWidth() &&
                wallpaperManager.getDesiredMinimumHeight() > wallpaper.getHeight()) {
            //add padding to wallpaper so background image scales correctly
            int xPadding = Math.max(0, wallpaperManager.getDesiredMinimumWidth() - wallpaper.getWidth()) / 2;
            int yPadding = Math.max(0, wallpaperManager.getDesiredMinimumHeight() - wallpaper.getHeight()) / 2;
            Bitmap paddedWallpaper = Bitmap.createBitmap(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight(), Bitmap.Config.ARGB_8888);
            int[] pixels = new int[wallpaper.getWidth() * wallpaper.getHeight()];
            wallpaper.getPixels(pixels, 0, wallpaper.getWidth(), 0, 0, wallpaper.getWidth(), wallpaper.getHeight());
            paddedWallpaper.setPixels(pixels, 0, wallpaper.getWidth(), xPadding, yPadding, wallpaper.getWidth(), wallpaper.getHeight());

            wallpaperManager.setBitmap(paddedWallpaper);
        } else {
            wallpaperManager.setBitmap(wallpaper);
        }
    } catch (IOException e) {
        Log.e(TAG,"failed to set wallpaper");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值