Draw text As Bitmap - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

Draw text As Bitmap

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.Canvas;

import android.graphics.Paint;
import android.os.Environment;
import android.util.Log;

public class Main {
    public static Bitmap textAsBitmap(Bitmap image, String text,
            float textSize, int textColor) {
        Paint paint = new Paint();
        paint.setTextSize(textSize);//from   ww  w  .j a va 2s.  c o  m
        paint.setColor(textColor);
        //paint.setTextAlign(Paint.Align.CENTER);
        paint.setAntiAlias(true);
        int width = (int) (paint.measureText(text) + 0.5f); // round
        float baseline = (int) (paint.ascent() + 0.5f);
        int height = (int) (baseline + paint.descent() + 0.5f);
        Bitmap newMapBitmap = image.copy(Bitmap.Config.ARGB_8888, true);
        try {
            Canvas canvas = new Canvas(newMapBitmap);
            //canvas.drawColor(Color.GREEN);
            canvas.drawText(text, 10, 20, paint);
        } catch (Exception e) {
            Log.e("textAsBitmap", e.getMessage());
        }

        String filename = "version.jpg";
        File sd = Environment.getExternalStorageDirectory();
        File dest = new File(sd, filename);

        try {
            FileOutputStream out = new FileOutputStream(dest);
            newMapBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newMapBitmap;
    }
}

Related Tutorials