我想设置一个特定的Drawable作为设备的壁纸,但所有的壁纸功能只接受位图。我不能使用WallpaperManager,因为我是pre 2.1。
另外,我的drawables是从网上下载的,并不存在于R.drawable中。
我想设置一个特定的Drawable作为设备的壁纸,但所有的壁纸功能只接受位图。我不能使用WallpaperManager,因为我是pre 2.1。
另外,我的drawables是从网上下载的,并不存在于R.drawable中。
当前回答
这将BitmapDrawable转换为Bitmap。
Drawable d = ImagesArrayList.get(0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
其他回答
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()
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
也许这能帮助到某人…
从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);
Android提供了一个非直接的解决方案:BitmapDrawable。为了获得位图,我们必须提供资源id R.drawable。flower_pic到BitmapDrawable,然后将其转换为Bitmap。
Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
这将BitmapDrawable转换为Bitmap。
Drawable d = ImagesArrayList.get(0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();