我有一个关于 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);
calculateInSampleSize是谷歌在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,并且还应该避免您看到的奇怪的缩放。如果没有,请告诉我,我会重新审视我所做的事情。
关于android - 从资源设置壁纸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673308/