rotate and scale bitmap in one operation - Android Graphics

Android examples for Graphics:Bitmap Rotate

Description

rotate and scale bitmap in one operation

Demo Code


//package com.java2s;

import android.graphics.Bitmap;

import android.graphics.Matrix;

public class Main {
    /**/*  w  w w .ja va  2s . com*/
     * 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