我想设置一个特定的Drawable作为设备的壁纸,但所有的壁纸功能只接受位图。我不能使用WallpaperManager,因为我是pre 2.1。
另外,我的drawables是从网上下载的,并不存在于R.drawable中。
我想设置一个特定的Drawable作为设备的壁纸,但所有的壁纸功能只接受位图。我不能使用WallpaperManager,因为我是pre 2.1。
另外,我的drawables是从网上下载的,并不存在于R.drawable中。
当前回答
在Kotlin中,最简单的方法是:
Drawable.toBitmap(width: Int, height: Int, config: Bitmap.Config?): Bitmap
是这样的:
val bitmapResult = yourDrawable.toBitmap(1,1,null)
在哪里,只需要一个可绘制的变量,没有资源,没有上下文,没有id
其他回答
1)可绘制位图:
Bitmap mIcon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon);
// mImageView.setImageBitmap(mIcon);
2)位图到可绘制:
Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);
非常简单的
Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
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()
ImageWorker库可以将位图转换为可绘制或base64,反之亦然。
val bitmap: Bitmap? = ImageWorker.convert().drawableToBitmap(sourceDrawable)
实现
在项目级别Gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
在应用级Gradle
dependencies {
implementation 'com.github.1AboveAll:ImageWorker:0.51'
}
您还可以从外部存储和检索位图/绘图/base64图像。
检查在这里。https://github.com/1AboveAll/ImageWorker/edit/master/README.md
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;
}