Wednesday, November 18, 2015

android - How to draw Text on a Canvas

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#b4aba7"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Draw Text"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.graphics.Canvas;
import android.graphics.Bitmap;

import java.util.Random;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private RelativeLayout mRelativeLayout;
    private Button mButton;
    private ImageView mImageView;
    private Random mRandom = new Random();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the Resources
        mResources = getResources();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButton = (Button) findViewById(R.id.btn);
        mImageView = (ImageView) findViewById(R.id.iv);

        // Set a click listener for Button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize a new Bitmap
                Bitmap bitmap = Bitmap.createBitmap(
                        600, // Width
                        300, // Height
                        Bitmap.Config.ARGB_8888 // Config
                );

                // Initialize a new Canvas instance
                Canvas canvas = new Canvas(bitmap);

                // Draw a solid color on the canvas as background
                canvas.drawColor(Color.WHITE);

                // Initialize a new Paint instance to draw the text
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                // Set the text color
                paint.setColor(Color.RED);
                paint.setAntiAlias(true);

                /*
                    public void setTextSize (float textSize)
                        Set the paint's text size. This value must be > 0

                    Parameters
                        textSize : set the paint's text size.
                */
                // Set the text size
                paint.setTextSize(125);

                /*
                    public void setTextAlign (Paint.Align align)
                        Set the paint's text alignment. This controls how the text is positioned
                        relative to its origin. LEFT align means that all of the text will be drawn
                        to the right of its origin (i.e. the origin specifieds the LEFT edge of
                        the text) and so on.

                    Parameters
                        align : set the paint's Align value for drawing text.
                */

                /*
                    Paint.Align
                        Align specifies how drawText aligns its text relative to
                        the [x,y] coordinates. The default is LEFT.

                        CENTER : The text is drawn centered horizontally on the x,y origin
                        LEFT : The text is drawn to the right of the x,y origin
                        RIGHT : The text is drawn to the left of the x,y origin
                */
                // Text alignment
                paint.setTextAlign(Paint.Align.CENTER);

                /*
                    Typeface
                        The Typeface class specifies the typeface and intrinsic style of a font.
                        This is used in the paint, along with optionally Paint settings like
                        textSize, textSkewX, textScaleX to specify how text appears when
                        drawn (and measured).
                */

                /*
                    public static Typeface create (Typeface family, int style)
                        Create a typeface object that best matches the specified existing typeface
                        and the specified Style. Use this call if you want to pick a new style from
                        the same family of an existing typeface object. If family is null,

                        this selects from the default font's family.
                    Parameters
                        family : May be null. The name of the existing type face.
                        style : The style (normal, bold, italic) of the typeface.
                            e.g. NORMAL, BOLD, ITALIC, BOLD_ITALIC
                    Returns
                        The best matching typeface.
                */

                // Initialize a typeface object to draw text on canvas
                Typeface typeface = Typeface.create(Typeface.SANS_SERIF,Typeface.BOLD_ITALIC);

                // Set the paint font
                paint.setTypeface(typeface);

                // Initialize a new EmbossMaskFilter instance
                EmbossMaskFilter filter = new EmbossMaskFilter(
                        new float[]{1,5,1}, // direction of the light source
                        0.5f, // ambient light between 0 to 1
                        10, // specular highlights
                        7.5f // blur before applying lighting
                );

                // Apply the MaskFilter to draw embossed text
                paint.setMaskFilter(filter);

                // Define the text to draw on canvas
                String txt = "ANDROID";

                /*
                    public void drawText (String text, float x, float y, Paint paint)
                        Draw the text, with origin at (x,y), using the specified paint. The origin
                        is interpreted based on the Align setting in the paint.

                    Parameters
                        text : The text to be drawn
                        x : The x-coordinate of the origin of the text being drawn
                        y : The y-coordinate of the baseline of the text being drawn
                        paint : The paint used for the text (e.g. color, size, style)
                */

                // calculate the y position of canvas to draw the text
                Rect rectangle = new Rect();

                /*
                    public void getTextBounds (String text, int start, int end, Rect bounds)
                        Return in bounds (allocated by the caller) the smallest rectangle that
                        encloses all of the characters, with an implied origin at (0,0).
                    Parameters
                        text : String to measure and return its bounds
                        start : Index of the first char in the string to measure
                        end : 1 past the last char in the string measure
                        bounds : Returns the unioned bounds of all the text. Must be allocated by
                            the caller.
                */
                paint.getTextBounds(
                        txt, // text
                        0, // start
                        txt.length(), // end
                        rectangle // bounds
                );

                // Initialize a new RadialGradient object
                RadialGradient gradient = new RadialGradient(
                        mRandom.nextInt(rectangle.right),
                        mRandom.nextInt(rectangle.bottom),
                        mRandom.nextInt(rectangle.right),
                        new int[]{
                                getRandomHSVColor(),
                                getRandomHSVColor(),
                                getRandomHSVColor(),
                                getRandomHSVColor(),
                                getRandomHSVColor()
                        },
                        null, // Stops position is undefined
                        Shader.TileMode.MIRROR // Shader tiling mode
                );

                // Apply the RadialGradient as paint shader
                paint.setShader(gradient);

                //Finally, Draw the text on the canvas at the horizontal and vertical center position
                canvas.drawText(
                        txt, // Text to draw
                        canvas.getWidth()/2, // x
                        canvas.getHeight()/2 + Math.abs(rectangle.height())/2, // y
                        paint // Paint
                );

                // Display the newly created bitmap on app interface
                mImageView.setImageBitmap(bitmap);
            }
        });
    }

    // Custom method to generate random HSV color
    protected int getRandomHSVColor(){
        // Generate a random hue value between 0 to 360
        int hue = mRandom.nextInt(361);

        // We make the color depth full
        float saturation = 1.0f;

        // We make a full bright color
        float value = 1.0f;

        // We avoid color transparency
        int alpha = 255;

        // Finally, generate the color
        int color = Color.HSVToColor(alpha,new float[]{hue,saturation,value});

        // Return the color
        return color;
    }
}
More android examples