如何将Drawable转换为Bitmap?

1093

我希望将某个特定的 Drawable 设为设备的壁纸,但所有的壁纸功能只接受 Bitmap。由于我的环境版本低于2.1,因此无法使用 WallpaperManager

此外,我的绘图对象是从网络下载而来的,而不是存储在 R.drawable 中的。


1
http://codingaffairs.blogspot.com/2016/06/how-to-convert-drawable-to-bitmap-in.html - Developine
1
https://dev59.com/NnA75IYBdhLWcg3w6Nr8#15555203 - Erfan Bagheri
22个回答

1

我在这个帖子上使用了一些答案,但其中一些并没有像预期的那样工作(也许它们在旧版本中起作用),但经过几次尝试和错误后,我想分享我的解决方案,使用一个扩展函数:

val markerOption = MarkerOptions().apply {
    position(LatLng(driver.lat, driver.lng))
    icon(R.drawabel.your_drawable.toBitmapDescriptor(context))
    snippet(driver.driverId.toString())
}
mMap.addMarker(markerOption)

这是扩展函数:

fun Int.toBitmapDescriptor(context: Context): BitmapDescriptor {
    val vectorDrawable = ResourcesCompat.getDrawable(context.resources, this, context.theme)
    val bitmap = vectorDrawable?.toBitmap(
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    return BitmapDescriptorFactory.fromBitmap(bitmap!!)
}

1
 // 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);
        }
    }
}

我认为你误读了问题。问题是如何从可绘制资源中获取位图,而不是系统相册。 - kc ochibili

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接