rotate and scale bitmap in one operation - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

rotate and scale bitmap in one operation

Demo Code

import android.graphics.Bitmap;
import android.graphics.Matrix;

public class Main {

  /**//from w w w. ja  va 2s  . c  o  m
   * max picture width
   */
  private static final int MAX_WIDTH = 400;
  /**
   * max picture height
   */
  private static final int MAX_HEIGHT = 300;

  /**
   * rotate and scale bitmap in one operation
   * 
   * @param source
   *          bitmap we want to scale and rotate
   * @param rotation
   *          rotation in degrees
   * @return transformed bitmap
   */
  public static Bitmap rotateAndScaleBitmap(Bitmap source, float rotation, int maxWidth, int maxHeight) {
    float scale;
    if (maxHeight != 0 && maxWidth != 0) {
      scale = Math.min(maxWidth / (float) source.getWidth(), maxHeight / (float) source.getHeight());
    } else {
      scale = Math.min(MAX_WIDTH / (float) source.getWidth(), MAX_HEIGHT / (float) source.getHeight());
    }
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);
    matrix.postRotate(rotation);
    Bitmap result = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
    return result;
  }

}

Related Tutorials