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.Canvas;

import android.graphics.Paint;

import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.DisplayMetrics;

public class Main {
    /**
     * Create round, coloured bitmap with text embedded.
     * @param circleColor The color to use.
     * @param diameterDP The diameter of the circle.
     * @param text The text to embed.
     * @return Bitmap showing a text.
     */
    public static Bitmap generateCircleBitmap(int circleColor, float diameterDP, String text) {
        /**
         *
         * http://stackoverflow.com/questions/31168636/rounded-quickcontactbadge-with-text
         */
        final int textColor = 0xffffffff;

        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float diameterPixels = diameterDP * (metrics.densityDpi / 160f);
        float radiusPixels = diameterPixels / 2;

        // Create the bitmap
        Bitmap output = Bitmap.createBitmap((int) diameterPixels, (int) diameterPixels, Bitmap.Config.ARGB_8888);

        // Create the canvas to draw on
        Canvas canvas = new Canvas(output);
        canvas.drawARGB(0, 0, 0, 0);

        // Draw the circle
        final Paint paintC = new Paint();
        paintC.setAntiAlias(true);
        paintC.setColor(circleColor);
        canvas.drawCircle(radiusPixels, radiusPixels, radiusPixels, paintC);

        // Draw the text
        if (text != null && text.length() > 0) {
            final Paint paintT = new Paint();
            paintT.setColor(textColor);
            paintT.setAntiAlias(true);
            paintT.setTextSize(radiusPixels * 2);
            paintT.setTypeface(Typeface.SANS_SERIF);
            final Rect textBounds = new Rect();
            paintT.getTextBounds(text, 0, text.length(), textBounds);
            canvas.drawText(text, radiusPixels - textBounds.exactCenterX(),
                    radiusPixels - textBounds.exactCenterY(), paintT);
        }

        return output;
    }
}