0

我有设置壁纸的代码(需要 android.permission.SET_WALLPAPER)

// this is inside activity
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this); 
wallpaperManager.setBitmap(bitmap);

我的问题是,如何调整此代码以将壁纸设置为适合屏幕两个选项:

  1. 如果图像分辨率低于屏幕分辨率 - 拉伸它。
  2. 如果图像分辨率高于屏幕分辨率 - 将其缩小。

注意:在将其设置为墙纸之前,我已经尝试将位图缩放到屏幕的分辨率,但实际上它看起来比不缩放更有价值。

4

1 回答 1

-1

我做了一个应用程序来设置壁纸,我尝试了很多东西......真正对我有用的是这个方法:

// Crop or inflate bitmap to desired device height and/or width
public Bitmap prepareBitmap(final Bitmap sampleBitmap,
                            final WallpaperManager wallpaperManager) {
    Bitmap changedBitmap = null;
    final int heightBm = sampleBitmap.getHeight();
    final int widthBm = sampleBitmap.getWidth();
    final int heightDh = wallpaperManager.getDesiredMinimumHeight();
    final int widthDh = wallpaperManager.getDesiredMinimumWidth();
    if (widthDh > widthBm || heightDh > heightBm) {
        final int xPadding = Math.max(0, widthDh - widthBm) / 2;
        final int yPadding = Math.max(0, heightDh - heightBm) / 2;
        changedBitmap = Bitmap.createBitmap(widthDh, heightDh,
                Bitmap.Config.ARGB_8888);
        final int[] pixels = new int[widthBm * heightBm];
        sampleBitmap.getPixels(pixels, 0, widthBm, 0, 0, widthBm, heightBm);
        changedBitmap.setPixels(pixels, 0, widthBm, xPadding, yPadding,
                widthBm, heightBm);
    } else if (widthBm > widthDh || heightBm > heightDh) {
        changedBitmap = Bitmap.createBitmap(widthDh, heightDh,
                Bitmap.Config.ARGB_8888);
        int cutLeft = 0;
        int cutTop = 0;
        int cutRight = 0;
        int cutBottom = 0;
        final Rect desRect = new Rect(0, 0, widthDh, heightDh);
        Rect srcRect = new Rect();
        if (widthBm > widthDh) { // crop width (left and right)
            cutLeft = (widthBm - widthDh) / 2;
            cutRight = (widthBm - widthDh) / 2;
            srcRect = new Rect(cutLeft, 0, widthBm - cutRight, heightBm);
        } else if (heightBm > heightDh) { // crop height (top and bottom)
            cutTop = (heightBm - heightDh) / 2;
            cutBottom = (heightBm - heightDh) / 2;
            srcRect = new Rect(0, cutTop, widthBm, heightBm - cutBottom);
        }
        final Canvas canvas = new Canvas(changedBitmap);
        canvas.drawBitmap(sampleBitmap, srcRect, desRect, null);

    } else {
        changedBitmap = sampleBitmap;
    }
    return changedBitmap;
}

它来自本手册的代码,您将在其中找到更多正确调整图像大小的方法。

于 2018-02-21T14:32:57.650 回答