这是我的 xml 文件:我尝试访问的 ImageView
<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" />
这是我的代码..请检查代码并让我知道我哪里做错了,我在互联网上进行了搜索,只是无法尝试弄清楚如何制作位图对象并在 ImageView 上绘制 Canvas
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);
}
}
}
最佳答案
如果您在该行上收到 NullPointerException,则意味着 img
为 null,这意味着 findViewById(R.id.imgview);
返回 null,或者 onDraw 正在作为 super(context);
的一部分执行(不确定情况是否如此)。
关于java - 位图创建空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28284434/