draw Text To Bitmap - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

draw Text To Bitmap

Demo Code


//package com.java2s;

import java.io.FileOutputStream;

import java.io.OutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;

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

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

import android.os.Environment;

public class Main {
    private static int pictureNum = 1;

    public static Bitmap drawTextToBitmap(Bitmap bitmap, String gText) {
        OutputStream outStream = null;
        Bitmap.Config bitmapConfig = bitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }//w w  w  .j  a  va2 s.c om
        String dataPath = Environment.getExternalStorageDirectory()
                .toString()
                + "/SignChat/Temp/temp"
                + "0"
                + pictureNum
                + ".jpg";

        try {

            FileOutputStream out = new FileOutputStream(dataPath);

            // NEWLY ADDED CODE STARTS HERE [
            Canvas canvas = new Canvas(bitmap);

            Paint paint = new Paint();
            paint.setColor(Color.WHITE); // Text Color
            paint.setStrokeWidth(12); // Text Size
            paint.setXfermode(new PorterDuffXfermode(
                    PorterDuff.Mode.SRC_OVER)); // Text

            canvas.drawBitmap(bitmap, 0, 0, paint);
            canvas.drawText("Testing...", 10, 10, paint);

            bitmap.compress(CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}

Related Tutorials