Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

import android.graphics.Canvas;

import android.graphics.Matrix;

import android.graphics.PixelFormat;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class Main {
    public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
        if (null == drawable || w < 0 || h < 0) {
            return null;
        }

        try {
            int width = drawable.getIntrinsicWidth();
            int height = drawable.getIntrinsicHeight();
            Bitmap oldbmp = drawableToBitmap(drawable);
            Matrix matrix = new Matrix();
            float scaleWidth = 1;
            float scaleHeight = 1;
            if (w > 0) {
                scaleWidth = ((float) w / width);
            }
            if (h > 0) {
                scaleHeight = ((float) h / height);
            }

            matrix.postScale(scaleWidth, scaleHeight);
            Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);
            return new BitmapDrawable(newbmp);
        } catch (Exception e) {
            return null;
        }
    }

    static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }
}