3

我正在尝试从资源创建位图并在其上绘制一个简单的文本。代码编译并运行,但是当我单击按钮时,应用程序在 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;
    }

}
4

2 回答 2

1

资源位图是不可变的。在写入之前,您应该将其复制到可变位图。这是本教程的代码片段:

  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);
于 2013-07-01T03:43:51.363 回答
0

为了节省一些内存,你应该输入可变参数,而不是解码和复制,BitmapFactory.Option如下BitmapFactory所示:

...
Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap marked= BitmapFactory.decodeResource(getResources(), R.drawable.my_image, opt);
...

这应该返回一个 Mutable,随时可以使用和更改,Bitmap.

于 2013-07-30T16:44:45.260 回答