获取桌面壁纸作为App背景

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LikeSidehu/article/details/51225524

    最近做app领导要求所有app都要用桌面壁纸来作为app的背景图。于是写了以下代码来实现:

private void setBackground() {
try {

LinearLayout rl = (LinearLayout) findViewById(R.id.fm_main);
WallpaperManager wm = WallpaperManager.getInstance(this);
Drawable d = wm.getDrawable();

if (d != null) {

rl.setBackground(d);
} else {
rl.setBackgroundResource(R.drawable.wallpaper);
}

}

这样做当然是可以,但是发现背景图会被严重压缩,跟桌面上的壁纸效果相差太大。

用各种压缩,拉伸,裁剪都不起作用,简直要抓狂啊。后来想,launcher里面既然可以做到,为何不模仿launcher的做法呢?

于是查看launcher设置壁纸的源码,发现自定义了一个Drawable:

static class WallpaperDrawable extends Drawable {


        Bitmap mBitmap;
        int mIntrinsicWidth;
        int mIntrinsicHeight;

public void setBitmap(Bitmap bitmap) {
            mBitmap = bitmap;
            if (mBitmap == null)
                return;
            mIntrinsicWidth = mBitmap.getWidth();
            mIntrinsicHeight = mBitmap.getHeight();
        }

@Override
        public void draw(Canvas canvas) {
            if (mBitmap == null) return;
            int width = canvas.getWidth();
            int height = canvas.getHeight() ;

      int x = (width - mIntrinsicWidth) / 2;
            int y = (height - mIntrinsicHeight) / 2;
            canvas.drawBitmap(mBitmap, x, y, null);
        }

@Override
        public int getOpacity() {
            return android.graphics.PixelFormat.OPAQUE;
        }

 @Override
        public void setAlpha(int alpha) {
            // Ignore
        }


        @Override
        public void setColorFilter(ColorFilter cf) {
            // Ignore
        }

结合自己的一些代码,最终解决了背景倍压扁的问题:

// drawable转bitmap
private static Bitmap drawableToBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();

Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(width, height, config);
Canvas canvas = new Canvas(bitmap);

drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
}

最后,修改setBackground方法:

private void setBackground() {
try {

LinearLayout rl = (LinearLayout) findViewById(R.id.fm_main);
WallpaperManager wm = WallpaperManager.getInstance(this);
Drawable d = wm.getDrawable();

if (d != null) {

Bitmap bitmap = drawableToBitmap(d);
WallpaperDrawable wd = new WallpaperDrawable();
wd.setBitmap(bitmap);

rl.setBackground(d);

} else {
rl.setBackgroundResource(R.drawable.wallpaper);
}

}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页