简体   繁体   中英

How to resize the image in Android bitmap?

I want to show a heart shape Image on an Image similar to following image: 在此处输入图片说明

I tried createScaledBitmap but it's not working. Here is my code:

@Override
public Bitmap transform(Bitmap bitmap) {
    // TODO Auto-generated method stub
    synchronized (ImageTransform.class) {
        if (bitmap == null) {
            return null;
        }
        Bitmap resultBitmap = bitmap.copy(bitmap.getConfig(), true);
        Bitmap bitmapImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_heart);
        Bitmap.createScaledBitmap(
                bitmapImage, 1, 1, true);

        Canvas canvas = new Canvas(resultBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(40);
        paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.BLACK);


            canvas.drawText("$250", 10, 400, paint);
            canvas.drawBitmap(bitmapImage, 460, 45, null);


        bitmap.recycle();
        return resultBitmap;
    }
}

Image is not scaling I can see very big Image. Above code is in Transformation class of Picasso .

Why it should scale your bitmap image?

Lets go through your code:

    Bitmap resultBitmap = bitmap.copy(bitmap.getConfig(), true);

ok this is the bitmap that will have hearth added

    Bitmap bitmapImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_heart);

You read your hearth image here in order to add it to "main" image later

    Bitmap.createScaledBitmap(
            bitmapImage, 1, 1, true);

This is redundant call because you omit here the result of method call...

    Canvas canvas = new Canvas(resultBitmap);

here we got new canvas with mutable bitmap for modifications

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.FILL);
    paint.setTextSize(40);
    paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.BLACK);
    canvas.drawText("$250", 10, 400, paint);

You draw price here and it is ok

    canvas.drawBitmap(bitmapImage, 460, 45, null);

You draw here a bitmap image that you've read from resources without modifications

    bitmap.recycle();

This is redundant from Android 3.0

    return resultBitmap;

Return of your image...

As you see you have a method call: Bitmap.createScaledBitmap(bitmapImage, 1, 1, true); That really does nothing. Replace it with: bitmapImage = Bitmap.createScaledBitmap(bitmapImage, 1, 1, true); and it should be fine.

If you want to optimize your memory usage here (because you are creating here 3 bitmaps instead of one) read THIS ARTICLE . Hope that helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM