从资源设置壁纸

时间:2013-05-21 15:04:42

标签: android wallpaper

我对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();
  }  
}

1 个答案:

答案 0 :(得分:1)

我发现设置壁纸时没有任何缩放问题的最佳方法(通常看起来完全是随意的,正如您在分辨率大小相同时看到的那样)是使用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);

calculateInSampleSize是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,并且还应避免您看到的奇怪缩放。如果没有,请告诉我,我会再看看我做了什么。