我有以下代码,用于设置图像并在图像顶部绘制文本。但是我似乎无法让代码工作,我的程序以 NPE 退出(参见 CATLOG)。似乎 createImage 方法中的 setImageBitmap() 行导致了这种情况,但我似乎无法弄清楚原因。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Intent intent = getIntent();
int position = intent.getIntExtra("position", 0);
Log.w("myApp", "" + position);
final ImageView iv_ttx = (ImageView) findViewById(R.id.iv_ttx);
final int[] imgSizeIds = new int[] { R.drawable.img1,
R.drawable.img2, R.drawable.img3 };
// Create Paint Object
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
paint.setTextSize(75);
// Create or Load Bitmap
iv_ttx.setImageResource(imgSizeIds[position]);
originalBitmap = BitmapFactory.decodeResource(getResources(),
imgSizeIds[position]);
image = originalBitmap.copy(Bitmap.Config.RGB_565, true);
iv_ttx.setImageBitmap(image);
et_top = (EditText) findViewById(R.id.top_txt);
Button btntop = (Button) findViewById(R.id.btntop);
// Set OnClickListeners
btntop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String user_text = et_top.getText().toString();
createImage(user_text);
}
});
public Bitmap createImage(String user_text) {
// canvas object with bitmap image as constructor
Canvas canvas = new Canvas(image);
canvas.drawText("" + user_text, 400, 400, paint);
iv_ttx.setImageBitmap(image);
return image;
}
现在对于有趣的部分,如果我删除 iv_ttx.setImageBitmap(image) 行,在我单击顶部按钮后大约 30 秒左右,文本似乎出现在图像顶部,或者如果我一直持续单击它,有什么想法吗?
目录:
09-06 22:14:39.197: E/AndroidRuntime(21242): FATAL EXCEPTION: main
09-06 22:14:39.197: E/AndroidRuntime(21242): java.lang.NullPointerException
09-06 22:14:39.197: E/AndroidRuntime(21242): at com.meme.hdmeme.MemeEditor.createImage(MemeEditor.java:72)
09-06 22:14:39.197: E/AndroidRuntime(21242): at com.meme.hdmeme.MemeEditor$1.onClick(MemeEditor.java:63)
09-06 22:14:39.197: E/AndroidRuntime(21242): at android.view.View.performClick(View.java:4204)
09-06 22:14:39.197: E/AndroidRuntime(21242): at android.view.View$PerformClick.run(View.java:17355)
09-06 22:14:39.197: E/AndroidRuntime(21242): at android.os.Handler.handleCallback(Handler.java:725)
09-06 22:14:39.197: E/AndroidRuntime(21242): at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 22:14:39.197: E/AndroidRuntime(21242): at android.os.Looper.loop(Looper.java:137)
09-06 22:14:39.197: E/AndroidRuntime(21242): at android.app.ActivityThread.main(ActivityThread.java:5214)
09-06 22:14:39.197: E/AndroidRuntime(21242): at java.lang.reflect.Method.invokeNative(Native Method)
09-06 22:14:39.197: E/AndroidRuntime(21242): at java.lang.reflect.Method.invoke(Method.java:511)
09-06 22:14:39.197: E/AndroidRuntime(21242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
09-06 22:14:39.197: E/AndroidRuntime(21242): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
09-06 22:14:39.197: E/AndroidRuntime(21242): at dalvik.system.NativeStart.main(Native Method)