我想设置一个特定的Drawable作为设备的壁纸,但所有的壁纸功能只接受位图。我不能使用WallpaperManager,因为我是pre 2.1。
另外,我的drawables是从网上下载的,并不存在于R.drawable中。
我想设置一个特定的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);
其他回答
方法1:你可以像这样直接转换成位图
Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
方法2:你甚至可以把资源转换成可绘制的,从那里你可以得到像这样的位图
Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.logo)).getBitmap();
对于API > 22 getDrawable方法移动到ResourcesCompat类,因此你可以这样做
Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();
BitmapFactory.decodeResource()自动缩放位图,因此您的位图可能会变得模糊。为了防止结垢,请这样做:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
or
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
下面是@Chris提供的答案的Kotlin版本。Jenkins在这里:https://stackoverflow.com/a/27543712/1016462
fun Drawable.toBitmap(): Bitmap {
if (this is BitmapDrawable) {
return bitmap
}
val width = if (bounds.isEmpty) intrinsicWidth else bounds.width()
val height = if (bounds.isEmpty) intrinsicHeight else bounds.height()
return Bitmap.createBitmap(width.nonZero(), height.nonZero(), Bitmap.Config.ARGB_8888).also {
val canvas = Canvas(it)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
}
}
private fun Int.nonZero() = if (this <= 0) 1 else this
// get image path from gallery
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
super.onActivityResult(requestCode, resultcode, intent);
if (requestCode == 1) {
if (intent != null && resultcode == RESULT_OK) {
Uri selectedImage = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
//display image using BitmapFactory
cursor.close(); bmp = BitmapFactory.decodeFile(filepath);
iv.setBackgroundResource(0);
iv.setImageBitmap(bmp);
}
}
}
如果您正在使用kotlin,请使用以下代码。它会工作
//使用image路径
val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap