Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;

import android.text.TextPaint;

public class Main {
    /**
     * Draw text on canvas. Shade if text too long to fit.
     *
     * @param canvas The canvas to draw in.
     * @param text The text to draw.
     * @param x The x coordinate.
     * @param y The y coordinate.
     * @param textPaint The paint to draw with.
     * @param availableWidth The available width for the text
     */
    public static void drawText(Canvas canvas, String text, float x, float y, TextPaint textPaint,
            int availableWidth) {
        text = text.replaceAll("\\r?\\n", " ");
        final TextPaint localTextPaint = new TextPaint(textPaint);
        final float pixelsToShade = 1.5F * localTextPaint.getTextSize();
        int characters = text.length();

        if (localTextPaint.measureText(text) > availableWidth) {
            Paint.Align align = localTextPaint.getTextAlign();
            float shaderStopX;
            characters = localTextPaint.breakText(text, true, availableWidth, null);
            if (align == Paint.Align.LEFT) {
                shaderStopX = x + availableWidth;
            } else if (align == Paint.Align.CENTER) {
                float[] measuredWidth = new float[1];
                characters = localTextPaint.breakText(text, true, availableWidth, measuredWidth);
                shaderStopX = x + (measuredWidth[0] / 2);
            } else { // align == Paint.Align.RIGHT
                shaderStopX = x;
            }
            // Hex 0x60000000 = first two bytes is alpha, gives semitransparent
            localTextPaint.setShader(new LinearGradient(shaderStopX - pixelsToShade, 0, shaderStopX, 0,
                    localTextPaint.getColor(), localTextPaint.getColor() + 0x60000000, Shader.TileMode.CLAMP));
        }
        canvas.drawText(text, 0, characters, x, y, localTextPaint);
    }
}