java - 使用 BitmapFactory 在 Canvas 上 onDraw 时出错

标签 java android canvas android-bitmap

我想使用 bitmapFactory 在 Canvas 上绘制图像,但它给了我一个错误。

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference
        at android.graphics.BaseCanvas.throwIfCannotDraw(BaseCanvas.java:54)
        at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:226)
        at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:78)
        at com.example.canvastest.GameView.onDraw(GameView.java:23)

我尝试用实际的绘制对象更改空绘制,但效果不好。
我也尝试过使用 Rect 来填充空间,但效果也不好。

    private Bitmap bmp;
    public GameView(Context context) {
        super(context);
        bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.BLUE);
        canvas.drawBitmap(bmp, 10, 10, null);
    }

最佳答案

尝试创建方法init(Context context),如下所示:

public void init(Context context) {
    this.context = context;
    bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
}

然后:

public GameView(Context context) {
    super(context);
    init(context);
}

public GameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}

public GameView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init(context);
}

关于java - 使用 BitmapFactory 在 Canvas 上 onDraw 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55992521/

相关文章:

java - setDisplayHomeAsUpEnabled 不显示带有自定义操作栏 View 的后退箭头

java - 将 ListFragment 和 Fragment 与仅接受 fragment 的 TabsPagerAdapter 结合起来

java - scala模板 Play Framework 中的if语句

java - 我需要一些关于 Big O 的说明

java - 扩展 Button 类以创建单例

android - 即使是单次使用,我也应该使用 XML 资源吗?

javascript - 如何更改 ChartJS 3 中饼图段悬停上的光标?

javascript - Onload() 处理程序在 IE 中没有响应

java - 在新线程上绘图( Canvas 很好,但在 jpanel 上无法正常工作)

java - PIG 聚合函数 - OutOfMemory : Java Heap Space