get Mask Icon - Android Graphics

Android examples for Graphics:Paint

Description

get Mask Icon

Demo Code


//package com.java2s;

import android.content.Context;
import android.graphics.Bitmap;

import android.graphics.Canvas;

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

public class Main {

    public static Bitmap getMaskIcon(Context context, Bitmap bitmap,
            Bitmap maskBitmap, Bitmap cover) {
        try {/*from  w ww . j ava  2s  . co  m*/
            if (maskBitmap == null) {
                return null;
            }
            int maskW = maskBitmap.getWidth();
            int maskH = maskBitmap.getHeight();
            Bitmap temp = Bitmap.createBitmap(maskW, maskH,
                    Bitmap.Config.ARGB_8888);
            Canvas canvasTemp = new Canvas(temp);

            if (bitmap != null) {

                int width = bitmap.getWidth();
                int height = bitmap.getHeight();

                if (width == 0 || height == 0) {
                    return null;
                }
                Matrix matrix = new Matrix(); 
                float scale = 1.0f;
                int offsetCutX = 0;
                int offsetCutY = 0;
                if (width > height) {
                    offsetCutX = (width - height) / 2;
                    scale = (float) maskH / height;
                } else {
                    offsetCutY = (height - width) / 2;
                    scale = (float) maskW / width;
                }
                matrix.postScale(scale, scale);
                Bitmap newbmp = Bitmap.createBitmap(bitmap, offsetCutX,
                        offsetCutY, width - 2 * offsetCutX, height - 2
                                * offsetCutY, matrix, true); 

                final int drawTop = Math.max(0, maskH - newbmp.getHeight());
                final int drawLeft = Math.max(0,
                        (maskW - newbmp.getWidth()) / 2);
                canvasTemp.drawBitmap(newbmp, drawLeft, drawTop, null);
                matrix = null;
            }

            Paint paint = new Paint();
            PorterDuffXfermode xfermode = new PorterDuffXfermode(
                    PorterDuff.Mode.DST_IN);
            paint.setXfermode(xfermode);
            if (!maskBitmap.isRecycled()) {
                canvasTemp.drawBitmap(maskBitmap, 0, 0, paint);
            }

            if (cover != null) {
                canvasTemp.drawBitmap(cover, 0, 0, null);
            }
            return temp;
        } catch (Exception e) {
            //         LogUtils.log(TAG, e);
        } catch (OutOfMemoryError e) {
            //         LogUtils.log(TAG, e);
        }
        return null;
    }
}

Related Tutorials