我想设置一个特定的Drawable作为设备的壁纸,但所有的壁纸功能只接受位图。我不能使用WallpaperManager,因为我是pre 2.1。

另外,我的drawables是从网上下载的,并不存在于R.drawable中。


当前回答

也许这能帮助到某人…

从PictureDrawable到Bitmap,使用:

private Bitmap pictureDrawableToBitmap(PictureDrawable pictureDrawable){ 
    Bitmap bmp = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bmp); 
    canvas.drawPicture(pictureDrawable.getPicture()); 
    return bmp; 
}

... 这样执行的:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);

其他回答

也许这能帮助到某人…

从PictureDrawable到Bitmap,使用:

private Bitmap pictureDrawableToBitmap(PictureDrawable pictureDrawable){ 
    Bitmap bmp = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bmp); 
    canvas.drawPicture(pictureDrawable.getPicture()); 
    return bmp; 
}

... 这样执行的:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);

这将BitmapDrawable转换为Bitmap。

Drawable d = ImagesArrayList.get(0);  
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();

最新的androidx核心库(androidx.core:core-ktx:1.2.0)现在有一个扩展函数:Drawable. tobitmap(…)来将Drawable转换为Bitmap。

1)可绘制位图:

Bitmap mIcon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon);
// mImageView.setImageBitmap(mIcon);

2)位图到可绘制:

Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);

android-ktx有Drawable。toBitmap方法:https://android.github.io/android-ktx/core-ktx/androidx.graphics.drawable/android.graphics.drawable.-drawable/to-bitmap.html

从芬兰湾的科特林

val bitmap = myDrawable.toBitmap()