razu
razu

Reputation: 120

Resizing bitmap

I am working on an android project. When i am trying to resizing a bitmap the app unfortunately stopped and in Logcat giving a message "only the mutable bitmap can resize". I tried to convert my bitmap into a mutable bit still the same problem.What may be the solution. my code :

public DrawingTheBall(Context context) {
    super(context);

    ball= BitmapFactory.decodeResource(getResources(),R.drawable.start_bg);;

}

@Override
protected void onDraw( Canvas canvas) {
    super.onDraw(canvas);

     ball.setWidth(canvas.getWidth());
     ball.setHeight(canvas.getHeight());


    Paint p=new Paint();
    canvas.drawBitmap(ball,0,0,p);


}

Upvotes: 0

Views: 190

Answers (3)

hata
hata

Reputation: 12523

Bitmap.setWidth and Bitmap.setHeight are introduced from API19 (KitKat).

Didn't you set the minSdkVersion to 19 or later?

update:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
ball= BitmapFactory.decodeResource(getResources(), R.drawable.start_bg, options);

Upvotes: 1

michal.z
michal.z

Reputation: 2075

If you want to load a scaled down version of your bitmap resource into memory pass properly set BitmapFactory.Options to decodeResource method. Load a Scaled Down Version into Memory If you want to scale bitmap which you already have in memory use Bitmap#createScaledBitmap.

Upvotes: 0

Eugen Pechanec
Eugen Pechanec

Reputation: 38243

Since you only scale the original bitmap you might want to use the folllowing method

Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

Complete code:

Bitmap newBmp = Bitmap.createScaledBitmap(ball, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(newBmp, 0, 0, p);

Consider moving the "newBmp" line to another method such as onSizeChanged(...). onDraw(...) will get called pretty much all the time and it would be slow and wasteful to recreate the same bitmap all the time.

Upvotes: 2

Related Questions