如何使用壁纸getDrawingCache()

时间:2014-08-04 11:43:46

标签: android window android-wallpaper

我的应用程序是一个启动器,现在我需要一个当前视图的位图。 启动器的视图可以通过getDrawingCache()重试,如下面的

   Bitmap bitmap = Bitmap.createBitmap(screen_w, screen_h, Config.ARGB_8888 );       
   View decorview = getWindow().getDecorView(); 
   decorview.setDrawingCacheEnabled(true);    
   bitmap = decorview.getDrawingCache();  

但是位图只是启动器视图,不包含壁纸。

如何获得带壁纸的位图?

2 个答案:

答案 0 :(得分:1)

您可以使用WallpaperManager获取壁纸位图,并在其上方绘制启动器的视图。

private Bitmap getBackground(Activity activity)
{
    View decorView = activity.getWindow().getDecorView(); 
    Bitmap outBmp = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Bitmap.Config.ARGB_8888);

    decorView.setDrawingCacheEnabled(true);

    Bitmap launcherBmp = decorView.getDrawingCache();       
    Canvas canvas = new Canvas(outBmp);
    canvas.drawBitmap(getWallpaperBitmap(activity), 0, 0, null);
    canvas.drawBitmap(launcherBmp, 0, 0, null);

    decorView.setDrawingCacheEnabled(false);

    return outBmp;
}

private Bitmap getWallpaperBitmap(Context context)
{
    WallpaperManager wpMgr = WallpaperManager.getInstance(context);
    BitmapDrawable bmpDraw = (BitmapDrawable) wpMgr.getDrawable();
    return bmpDraw.getBitmap();
}

答案 1 :(得分:0)

好吧,我不得不说没有单一的API提供这个功能,用户必须复合两个位图,一个是壁纸部分,另一个是启动器的桌面视图。 一般来说,发射器将壁纸延伸到几个屏幕,所以我们必须让壁纸看到可见的部分。

以下是我的工作方式:

    //get wallpaper's visible part
    //@param screenCount  how many screens launcher has
    //@param screenCurrent  current screen index
    Bitmap wallpaper = 
       ((BitmapDrawable) WallpaperManager.getInstance(context).getDrawable()).getBitmap();
    float step = 0;
    step = (wallpaper.getWidth() - w) / (screenCount - 1);
    Bitmap wallpaperCurrent = 
    Bitmap.createBitmap(wallpaper, (int)(screenCurrent * step), 0, w, h);

    //get launcher's visible view bitmap
    View decorview = context.getWindow().getDecorView();     
    decorview.buildDrawingCache();
    Bitmap desktopBitmap = decorview.getDrawingCache(); 

    //compound bitmaps
    Bitmap compoundBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);

    Canvas canvas = new Canvas(compoundBitmap);  
    canvas.drawBitmap(wallpaperCurrent, 0, 0, null);
    canvas.drawBitmap(desktopBitmap, 0, 0, null);

    canvas.save(Canvas.ALL_SAVE_FLAG);
    canvas.restore();

    // return compoundBitmap