techno
techno

Reputation: 6500

Drawing Text on a Bitmap Obtained from Resource

I'm trying to create a Bitmap from a Resource and draw a simple text on it.The code compiles and runs but when i click the button the App crashed in the AVD,What can be the problem

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;
    }

}

Upvotes: 3

Views: 213

Answers (2)

apenasVB
apenasVB

Reputation: 1463

In order to save some memory, instead of decoding and copying, you should input the mutable parameter as BitmapFactory.Option to BitmapFactory as follows:

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

This should return a Mutable, ready to use and change at will, Bitmap.

Upvotes: 0

HalR
HalR

Reputation: 11073

Resource bitmaps are immutable. You should copy it over to a mutable bitmap before writing on it. Here is a code snippet from 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);

Upvotes: 1

Related Questions