我正在尝试从资源创建一个位图并在其上绘制一个简单的文本。代码编译并运行但是当我点击按钮时,应用程序在AVD中崩溃,可能是什么问题
package apc.examples;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_me);
}
public void showAboutMessage(View v)
{
Bitmap marked= BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
ImageView portrait = (ImageView) findViewById(R.id.imageView1);
Canvas canvas = new Canvas(marked);
canvas.drawBitmap(marked, 0, 0, null);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(10);
canvas.drawText("asfasf",0, 0, paint);
portrait.setImageBitmap(marked);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.about_me, menu);
return true;
}
}
答案 0 :(得分:1)
资源位图是不可变的。您应该在写入之前将其复制到可变位图。以下是this tutorial:
的代码段 Bitmap marked= BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
android.graphics.Bitmap.Config bitmapConfig =
marked.getConfig();
// set default bitmap config if none
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
答案 1 :(得分:0)
为了节省一些内存而不是解码和复制,您应该将可变参数作为BitmapFactory.Option
输入到BitmapFactory
,如下所示:
...
Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap marked= BitmapFactory.decodeResource(getResources(), R.drawable.my_image, opt);
...
这应该返回一个Mutable,随时可以使用并随意更改Bitmap
。