首页 > 解决方案 > 如何修复 int Bitmap getWidth() 的空引用错误

问题描述

我更新了我的 PaintView 代码,因为根据我的 android studio 错误日志,它说我需要扩展到 android.app.activity 但现在我的位图 getwidth() 中有一个空引用错误。我是 android 应用程序的新手,但据我了解,它没有返回对象,因为它找不到位图?这是我的 PaintView 类:

public class PaintView extends android.app.Activity{

    LayoutParams params;
    Path path = new Path();
    Paint br = new Paint();
    Bitmap background;
    Bitmap background2;


  public PaintView(Context context) {


      super();

        int maxHeight = 2000;
        int maxWidth = 1000;

       float scale = Math.min(((float) maxHeight / background.getWidth()), ((float) maxWidth / background.getHeight()));

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        background = Bitmap.createBitmap(background, 0, 0, background.getWidth(), background.getHeight(), matrix, true);
        background2 = Bitmap.createBitmap(background2, 0, 0, background2.getWidth(), background2.getHeight(), matrix, true);



        br.setColor(Color.GREEN);
        br.setStyle(Paint.Style.STROKE);
        br.setStrokeJoin(Paint.Join.ROUND);
        br.setStrokeWidth(10f);

        params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

    }

    private float getHeight() {
     int height = 5;
     return height;
    }

    private float getWidth() {
      int width = 5;
      return width;
    }


    //@Override
    public void onClick(View view) {
    Log.i("Hello", "Hello you!");
    }
}

标签: javaandroid

解决方案


bitmap在分配它之前,您在类的构造函数中使用它。

float scale = ... background.getWidth() ...
...
background = Bitmap.createBitmap(...)

推荐阅读