write Text to Bitmap - Android Graphics

Android examples for Graphics:Bitmap Create

Description

write Text to Bitmap

Demo Code


//package com.java2s;

import android.graphics.Bitmap;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;

public class Main {
    public static final int Center = 1;
    public static final int Left = 2;
    public static final int Top = 3;

    public static void writeText(Bitmap bitmap, String text,
            int horizontal, int vertical, TextPaint paint) {
        Canvas canvas = new Canvas(bitmap);
        if (horizontal == Center) {
            paint.setTextAlign(Align.CENTER);
        } else if (horizontal == Left) {
            paint.setTextAlign(Align.LEFT);
        } else {/*ww w. ja v a2  s.  com*/
            paint.setTextAlign(Align.RIGHT);
        }

        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        StaticLayout test = new StaticLayout(text, paint,
                bitmap.getWidth(), Alignment.ALIGN_NORMAL, 1, 1, true);
        float x = 0, y = 0;
        if (vertical == Center) {
            y = (canvas.getHeight() - test.getHeight()) / 2;
        } else if (vertical == Top) {
            y = 0;
        } else {
            y = canvas.getHeight() - test.getHeight();
        }
        if (horizontal == Center) {
            x = canvas.getWidth() / 2;
        } else if (horizontal == Left) {
            x = 0;
        } else {
            x = canvas.getWidth();
        }
        canvas.translate(x, y);
        test.draw(canvas);
    }
}

Related Tutorials