draw Text To Bitmap - Android Graphics

Android examples for Graphics:Bitmap String

Description

draw Text To Bitmap

Demo Code


//package com.java2s;

import android.graphics.Bitmap;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class Main {
    public static Bitmap drawTextToBitmap(Bitmap bitmap, String gText) {
        //Resources resources = gContext.getResources();
        //float scale = resources.getDisplayMetrics().density;

        android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }/*  w  w  w  .j a  v a  2  s  .c  o  m*/
        // resource bitmaps are imutable,
        // so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);
        // new antialised Paint
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // text color - #3D3D3D
        paint.setColor(Color.rgb(61, 61, 61));
        // text size in pixels
        paint.setTextSize((int) (21)); //* scale));
        // text shadow
        paint.setShadowLayer(2f, 1f, 1f, Color.WHITE);
        // draw text to the Canvas center
        //Rect bounds = new Rect();
        //paint.getTextBounds(gText, 0, gText.length(), bounds);
        int x = bitmap.getWidth() - 150;//bounds.width()) - 150;
        int y = bitmap.getHeight() - 27;//bounds.height()) - 30;
        // fill
        canvas.drawRect(x, y, x + 150, y + 27, paint);
        canvas.drawText(gText, x, y + 20, paint);
        return bitmap;
    }
}

Related Tutorials