2012-07-10 106 views
5

我正在開發一個應用程序,從圖庫中選擇一個圖像,然後將該圖像設置爲壁紙。但這裏的問題是,只有圖像的一部分被設置爲壁紙而不是整個圖像,但我想要將整個圖像設置爲壁紙。你能告訴我如何做到這一點嗎?如何適合整個圖像在屏幕上作爲壁紙

這裏是我的代碼...

public class Scaleimage extends Activity { 
    /** Called when the activity is first created. */ 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     String FileName; 
     File file = new File("/sdcard/pictures"); 
     File[] imageFiles = file.listFiles(); 
     if(imageFiles.length > 0) { 
      FileName = imageFiles[0].getName(); 
     final WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext()); 
     Bitmap myBitmap = BitmapFactory.decodeFile("/sdcard/pictures" + "/" + FileName); 

     DisplayMetrics displayMetrics = new DisplayMetrics(); 
     getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); 
     int height = displayMetrics.heightPixels; 
     int width = displayMetrics.widthPixels << 1; 
     myBitmap = Bitmap.createScaledBitmap(myBitmap,width, height, true); 
     try { 
      wallpaperManager.setBitmap(myBitmap); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 
+0

你正在創建自己的壁紙應用程序,還是你使用股票壁紙? – XGouchet 2012-07-10 07:26:53

回答

7

設置壁紙大小的圖像大小:

WallpaperManager wm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE); 
wm.setBitmap(bitmap); 
wm.suggestDesiredDimensions(w, h); 

,並記得添加權限:

<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/> 
<uses-permission android:name="android.permission.SET_WALLPAPER"/> 
+0

謝謝。它爲我工作。 – moDev 2013-05-18 07:27:33

+2

請注意來自'suggestDesiredDimensions()'方法文檔的消息:**「注意開發人員,他們似乎沒有閱讀過這個內容,這是爲了讓主屏幕知道他們想要什麼尺寸的壁紙,沒有人應該是調用這個!當然不是其他非壁紙的應用程序,這些應用程序應該檢索建議的大小,以便它們可以構建與之匹配的壁紙。「** – 2014-09-26 12:09:06

0

試試吧,我有測試它是工作希望它可以幫助你:

final WallpaperManager wallpaperManager = (WallpaperManager)getSystemService(
       Context.WALLPAPER_SERVICE);  

Bitmap myBitmap = Bitmap.createScaledBitmap(Const.cropped_bitmap, wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight(), true); 
wallpaperManager.suggestDesiredDimensions(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight()); 

try { 

    wallpaperManager.setBitmap(myBitmap); 
    Toast.makeText(CropImageActivity.this, CropImageActivity.this.getString(R.string.wallpaper_has_been_set), 0).show(); 
} catch (IOException e) { 
    e.printStackTrace(); 
    Toast.makeText(CropImageActivity.this, "Wallpaper not set", 0).show(); 
}