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.graphics.Bitmap;

import android.graphics.Canvas;

import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;

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

public class Main {
    /** Used to get the mask of a drawable */
    private static Paint maskPaint = null;
    /** Default canvas used to interact with bitmaps */
    private static Canvas canvas = new Canvas();

    /**
     * Get a mask of color {@code color} using the alpha channel of {@code source}.
     * @param ctx Context.
     * @param source Source {@link Drawable} containing the shape alpha channel.
     * @param color Color of the shape.
     * @return A {@link Bitmap} containing the shape of the given color.
     */
    public static Drawable getMask(Context ctx, Drawable source, int color) {
        return new BitmapDrawable(ctx.getResources(), getMask(drawableToBitmap(source), color));
    }

    /**
     * Get a mask of color {@code color} using the alpha channel of {@code source}.
     * @param source Source image containing the shape alpha channel.
     * @param color Color of the shape.
     * @return A {@link Bitmap} containing the shape of the given color.
     */
    private static Bitmap getMask(Bitmap source, int color) {
        Bitmap retVal;

        retVal = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        retVal.eraseColor(color);

        synchronized (canvas) {
            if (maskPaint == null) {
                maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            }

            canvas.setBitmap(retVal);
            canvas.drawBitmap(source, 0, 0, maskPaint);
        }

        return retVal;
    }

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

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