scale Bitmap Center Crop - Android Graphics

Android examples for Graphics:Bitmap Scale

Description

scale Bitmap Center Crop

Demo Code


//package com.java2s;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;

public class Main {
    static public Bitmap scaleCenterCrop(Bitmap source, int newHeight,
            int newWidth) {
        int sourceWidth = source.getWidth();
        int sourceHeight = source.getHeight();

        float xScale = (float) newWidth / sourceWidth;
        float yScale = (float) newHeight / sourceHeight;
        float scale = Math.max(xScale, yScale);

        // Now get the size of the source bitmap when scaled
        float scaledWidth = scale * sourceWidth;
        float scaledHeight = scale * sourceHeight;

        float left = (newWidth - scaledWidth) / 2;
        float top = (newHeight - scaledHeight) / 2;

        RectF targetRect = new RectF(left, top, left + scaledWidth, top
                + scaledHeight);//from ww w  .j a va 2s. co m

        Bitmap dest = Bitmap.createBitmap(newWidth, newHeight,
                source.getConfig());
        Canvas canvas = new Canvas(dest);
        canvas.drawBitmap(source, null, targetRect, null);

        return dest;
    }
}

Related Tutorials