android - 即使使用来自上下文的资源,BitmapFactory.decodeResource 也会返回 null

标签 android android-view android-drawable android-bitmap

我已经检查了所有其他类似的问题,但没有人帮助我。这是我获取位图的代码:

public class HachureView extends View {

  //...

    @Override
    protected void onDraw(Canvas canvas) {

       //...
       bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.hachure);
       bitmap.prepareToDraw();
       canvas.drawBitmap(bitmap, 0, 0, mPaint);
    }
}

这里是 hach​​ure.xml:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/hacure3"
    android:tileModeY="repeat" />

而 hacure3 是 drawable 文件夹中的 png 文件。

问题是 decodeResource 总是返回 null。

根据this使用来自 context.getResource() 的资源的问题解决了这个问题。但这对我不起作用。

我也试过this并清理了该项目,但它再次无法正常工作。

我刚刚发现一个技巧 here .虽然它工作正常,但这不是我的问题的答案,这就是为什么 decodeResource() 返回 null:

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

注意 1:我已将 hacure3.png 替换为其他 png 文件以及一些 Material Design 图标,但没有任何变化。

注意 2:hacure.xml 打开时,android studio 中的预览窗口会正确显示图像。

最佳答案

我遇到了同样的问题。原因是 Android Studio - 刚刚组装了错误的 APK,资源类损坏。清理/重建可能会有所帮助。

关于android - 即使使用来自上下文的资源,BitmapFactory.decodeResource 也会返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38430781/

相关文章:

android - 动态获取可绘制对象的原色以设置工具栏颜色

android - 使用圆角可绘制对象

java - 将文本链接到手机的拨号器 (Android)

java - 如何设置只有秒和小数的倒计时器?

android - 双向数据绑定(bind) : View is missing user defined type

android - 等到用户停止输入后再在搜索 View 中执行大量搜索

android - 在 Android Studio 的 "Gradle DSL method not found"中需要帮助

android - 如何使 LinearLayouts 可点击

android - 隐藏View的平移动画

android - 如何在 Kotlin 中设置一个带有复合可绘制对象的 TextView,它是一个 URL 图像,加载了 Glide?