我的wallpapermanager有一个简单的问题,在此站点上找不到答案。我有一个非常简单的代码,其中的图片是1280x800(平板电脑的显示屏)。运行代码时,我只会将图像的中心作为墙纸,就像放大了整个图片一样。为什么?谢谢!

package com.daniel.wallpaperPorsche;

import java.io.IOException;
import com.daniel.wallpaper.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.WallpaperManager;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

WallpaperManager myWallpaperManager = WallpaperManager.getInstance(this);

try {
     myWallpaperManager.setResource(R.drawable.porsche_911_1280x800_72dpi);

     Toast.makeText(getBaseContext(), "Success set as wallpaper", Toast.LENGTH_SHORT).show();

} catch (IOException e) {
     Toast.makeText(getBaseContext(), "Error set as wallpaper", Toast.LENGTH_SHORT).show();

  }
  super.onDestroy();
  }
}

最佳答案

我发现设置墙纸而没有任何缩放问题(通常看起来完全是任意的,就像您看到的分辨率大小相同时一样)的最佳方法是使用BitmapFactory。您将使用WallpaperManager.setBitmap代替WallpaperManager.setResource。

String path = "path/to/desired/wallpaper/file";
final BitmapFactory.Options options = new BitmapFactory.Options();

//The inJustDecodeBounds option tells the decoder to return null (no bitmap), but it does
//include the size of the image, letting us query for the size.

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

//wm = WallpaperManager
wm.suggestDesiredDimensions(decodedSampleBitmap.getWidth(), decodedSampleBitmap.getHeight());
wm.setBitmap(decodedSampleBitmap);


computeInSampleSize是Google实际上在android文档中提供的一种实现;他们的目标是有效地加载大型位图。您可以在这里阅读一些内容:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

不幸的是,它们的实现是废话,并且经常是错误的。我推荐这个。

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

    int multiplyHeight = 1;
    int multiplyWidth = 1;

    while (imageHeight >= reqHeight)
    {
        multiplyHeight++;
        imageHeight = imageHeight/2;
    }
    while (imageWidth >= reqWidth)
    {
        multiplyWidth++;
        imageWidth = imageWidth/2;
    }

    if (multiplyHeight > multiplyWidth)
        return multiplyHeight;
    else
        return multiplyWidth;

}


此方法对于加载大文件更有效,可以防止OutOfMemoryException异常,并且还应避免出现奇怪的缩放。如果没有,请告诉我,我将再看一下我所做的事情。

09-27 09:23