Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.app.Activity;

import android.content.res.Resources;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;

import android.graphics.Paint;
import android.graphics.Paint.Style;

import android.graphics.drawable.BitmapDrawable;

import android.util.DisplayMetrics;

public class Main {
    public static BitmapDrawable writeOnDrawable(Activity actv, Resources res, int drawableId, String text,
            int textSize) {

        Bitmap bm = BitmapFactory.decodeResource(res, drawableId).copy(Bitmap.Config.ARGB_8888, true);

        DisplayMetrics dm = new DisplayMetrics();
        actv.getWindowManager().getDefaultDisplay().getMetrics(dm);

        int pixelSize = (int) ((textSize * dm.scaledDensity));

        if (text.length() > 2) {
            pixelSize = (int) ((textSize * dm.scaledDensity) * (0.5 - (text.length() / 10)));
        }

        Paint paint = new Paint();
        paint.setStyle(Style.FILL);
        paint.setColor(Color.WHITE);
        paint.setTextSize(pixelSize);
        paint.setTextAlign(Paint.Align.CENTER);

        // float adjust = paint.measureText(text);

        Canvas canvas = new Canvas(bm);
        int xPos = (int) ((bm.getWidth() / 2));
        int yPos = (int) ((bm.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));

        canvas.drawText(text, xPos, yPos, paint);

        return new BitmapDrawable(res, bm);
    }
}