简体   繁体   English

位图创建空指针异常

[英]Bitmap create null pointer exception

Here is my xml file : Image view im trying to access 这是我的xml文件:尝试访问的图片视图

<ImageView
    android:layout_width="350dip"
    android:layout_height="400dip"
    android:id="@+id/imgview"
    android:background="@drawable/pattern"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

Here is my code.. kindly review the code and let me know where i am doin things wrong i have searched all over the internet just cant try to figure it out how to make bitmap object and draw canvas on image view 这是我的代码..请仔细检查代码,让我知道我在哪里做错了我在互联网上搜索过的东西,只是无法尝试弄清楚如何制作位图对象并在图像视图上绘制画布

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setContentView(new SampleView(this));
}

private static class SampleView extends View {

    private ImageView img;
    // CONSTRUCTOR
    public SampleView(Context context) {
        super(context);
        setFocusable(true);
       img = (ImageView)findViewById(R.id.imgview);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();

        canvas.drawColor(Color.GREEN);
  //I keep on getting null pointer exception here
        Bitmap b = Bitmap.createBitmap(img.getMeasuredWidth(),img.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        c.drawRect(0, 0, 200, 200, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        paint.setTextSize(40);
        paint.setTextScaleX(1.f);
        paint.setAlpha(0);
        paint.setAntiAlias(true);
        c.drawText("Your text", 30, 40, paint);
        paint.setColor(Color.RED);

        canvas.drawBitmap(b, 10,10, paint);
    }

   }
}

If you're getting a NullPointerException on that line, it means img is null, which either means findViewById(R.id.imgview); 如果在该行上收到NullPointerException,则意味着img为null,这意味着findViewById(R.id.imgview); returned null, or onDraw is being executed as part of super(context); 返回null,或者作为super(context);一部分执行onDraw super(context); (not sure if that's the case). (不确定情况是否如此)。

When width or height you want to have in your bitmap exceeds the size of device then you may get this error. 当您要在位图中包含的宽度或高度超过设备的大小时,您可能会收到此错误。 You should use createScaledBitmap . 您应该使用createScaledBitmap This will help you. 这将为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM