Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.content.Context;

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

import android.graphics.Canvas;

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

public class Main {
    /** Default canvas used to interact with bitmaps */
    private static Canvas canvas = new Canvas();

    /**
     * Resize a {@link Drawable} to the given size.<br />
     * Metrics and density are given by the {@link Resources} bount to this instance.
     * @param ctx Context.
     * @param id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
     * @param width Desired width in {@code dp}.
     * @param height Desired height in {@code dp}.
     * @return A scaled {@link Drawable}.
     */
    public static Drawable resizeDrawable(Context ctx, int id, int width, int height) {
        return resizeDrawable(ctx, ctx.getResources().getDrawable(id), width, height);
    }

    /**
     * Resize a {@link Drawable} to the given size.<br />
     * Metrics and density are given by the {@link Resources} bount to this instance.
     * @param ctx Context.
     * @param drawable {@link Drawable} to resize.
     * @param width Desired width in {@code dp}.
     * @param height Desired height in {@code dp}.
     * @return A scaled {@link Drawable}.
     */
    public static Drawable resizeDrawable(Context ctx, Drawable drawable, int width, int height) {
        Resources res = ctx.getResources();
        float density = res.getDisplayMetrics().density;

        //Get a bitmap from the drawable
        Bitmap bmp = drawableToBitmap(drawable);

        //Create a scaled bitmap
        bmp = Bitmap.createScaledBitmap(bmp, (int) (width * density), (int) (height * density), true);

        //Convert bitmap to drawable
        return new BitmapDrawable(res, bmp);
    }

    /**
     * Return the {@link Bitmap} representing the {@link Drawable}.
     * @param drawable Object to convert to {@link Bitmap}.
     * @return {@link Bitmap} representing the {@link Drawable}.
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap retVal;
        if (drawable instanceof BitmapDrawable) {
            //Easy
            retVal = ((BitmapDrawable) drawable).getBitmap();
        } else {
            retVal = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                    Bitmap.Config.ARGB_8888);

            synchronized (canvas) {
                canvas.setBitmap(retVal);
                drawable.draw(canvas);
            }
        }
        return retVal;
    }
}