Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

import android.graphics.Canvas;

import android.graphics.Matrix;
import android.graphics.Paint;

public class Main {
    public static Bitmap scaleBitmapForDevice(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }

        float density = Resources.getSystem().getDisplayMetrics().density;
        int newWidth = (int) (bitmap.getWidth() * density);
        int newHeight = (int) (bitmap.getHeight() * density);
        /*
        Bitmap resizeBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
         */
        /**
         * http://stackoverflow.com/questions/4821488/bad-image-quality-after-resizing-scaling-bitmap#7468636
         */
        Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);

        float ratioX = newWidth / (float) bitmap.getWidth();
        float ratioY = newHeight / (float) bitmap.getHeight();
        float middleX = newWidth / 2.0f;
        float middleY = newHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2,
                new Paint(Paint.FILTER_BITMAP_FLAG));
        bitmap.recycle();

        return scaledBitmap;
    }
}