0

I don't want to insert an imageview into my view, I just want to set a bitmap as the background of my view. But I want the bitmap centerCropped. By default the bitmap background is stretched to fit the bounds of the view.

Prem
  • 3,373
  • 7
  • 29
  • 43

1 Answers1

1

You can do this by implementing a custom background drawable.

I implemented a subclass of BitmapDrawable that centerCrops the Bitmap (basically overriding the onDraw(Canvas) mehthod).

code:

package com.github.premnirmal;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;

/**
 * A subclass of bitmap drawable that scales the bitmap to CenterCrop
 * Copyright Prem Nirmal 2016 MIT License
 * @author PremNirmal
 */
public class CenterCropBitmapDrawable extends BitmapDrawable {

  private final int viewWidth, viewHeight;

  public CenterCropBitmapDrawable(Resources res, Bitmap bitmap, int viewWidth, int viewHeight) {
    super(res, bitmap);
    this.viewWidth = viewWidth;
    this.viewHeight = viewHeight;
  }

  @Override public void draw(Canvas canvas) {
    final Matrix drawMatrix = new Matrix();
    final int dwidth = getIntrinsicWidth();
    final int dheight = getIntrinsicHeight();

    final int vwidth = viewWidth;
    final int vheight = viewHeight;

    float scale;
    float dx = 0, dy = 0;
    int saveCount = canvas.getSaveCount();
    canvas.save();
    if (dwidth * vheight > vwidth * dheight) {
      scale = (float) vheight / (float) dheight;
      dx = (vwidth - dwidth * scale) * 0.5f;
    } else {
      scale = (float) vwidth / (float) dwidth;
      dy = (vheight - dheight * scale) * 0.5f;
    }

    drawMatrix.setScale(scale, scale);
    drawMatrix.postTranslate(Math.round(dx), Math.round(dy));
    canvas.concat(drawMatrix);

    canvas.drawBitmap(getBitmap(), 0, 0, getPaint());

    canvas.restoreToCount(saveCount);
  }
}
Prem
  • 3,373
  • 7
  • 29
  • 43
  • can you add this code instead of putting a link? This way future readers will still see the code (in case the gist gets deleted). – petey May 03 '16 at 20:26