我已经检查了所有其他类似的问题,但没有人帮助我。这是我获取位图
的代码:
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);
}
}
这里是 hachure.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/