将可绘制资源图像转换为位图。

188

我试图使用Notification.Builder.setLargeIcon(bitmap)方法并传入一张位图图片。我有一张我想要使用的图片存在drawable文件夹中,那么我该如何将其转换成位图图片?

8个回答

429

你可能想要使用Notification.Builder.setLargeIcon(Bitmap),对吗? :)

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);

这是一种将资源图像转换为Android Bitmap的好方法。


2
为什么不点击“编辑”按钮修正问题呢?(这只是一个未来的建议 - 我已经为这个问题做了。我建议你编辑你的回答,不要批评他们的错别字。我不会替你做这件事。)另外,赞一个,因为你有一个可行的答案 :) - ArtOfWarfare
1
我不认为这是正确的“通用答案”——至少自从Android开始支持矢量可绘制对象以来不是这样。 - roberto tomás
实施解决方案后,我得到了以下信息... ... E/CommitToConfigurationOperation: 快照令牌格式不正确(大小): ... E/NotificationService: 不发布具有icon==0的通知:Notification(pri=0 contentView=null vibrate=null sound=content://settings/system/notification_sound defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE) ... E/NotificationService: 警告:在未来的版本中,这将导致应用程序崩溃:... - Bhuro

49
Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

自API 22以来,getResources().getDrawable()已被弃用,因此我们可以使用以下解决方案。

Drawable vectorDrawable = VectorDrawableCompat.create(getResources(), R.drawable.logo,  getContext().getTheme());
Bitmap myLogo = ((BitmapDrawable) vectorDrawable).getBitmap();

1
它告诉我无法将bitmapDrawable解析为类型。 - user2424370
嗨@20Cents,你试过这个网址吗?https://dev59.com/fnXYa4cB1Zd3GeqP8qUq - AndyW
如果您在bitmapDrawable上收到“无法解析为类型”的错误,请按ctrl+shift+O。祝好! - portfoliobuilder
不幸的是,这个方法会使我的应用程序崩溃! - Fahad Alduraibi
getDrawable已被弃用 - Junior Mayhé

14
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);

Context 可以是你当前的 Activity


2
而对于矢量可绘制图形呢? - roberto tomás

9

以下是在Android中将Drawable资源转换为位图的另一种方法:

Drawable drawable = getResources().getDrawable(R.drawable.input);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

2
你的解决方案和AndyW的有什么不同吗?它们是一样的! - Fahad Alduraibi
我尝试了这个,但它产生了一个错误:java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable - dkoukoul

8

首先创建位图图像

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

现在在通知构建器图标中设置位图...
Notification.Builder.setLargeIcon(bmp);

1
如果有人正在寻找Kotlin版本的大图标,可以使用这个。
val largeIcon = BitmapFactory.decodeResource(context.resources, R.drawable.my_large_icon)

0
res/drawable 文件夹中, 1. 创建一个新的 Drawable 资源2. 输入文件名。
将创建一个新文件,位于 res/drawable 文件夹内。
将以下代码替换为新创建的文件中的代码,并用您的可绘制文件名称替换 ic_action_back
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_back"
    android:tint="@color/color_primary_text" />

现在,您可以使用资源ID R.id.filename

0
尝试以下内容:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.your_image_id);

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