Example usage for android.text TextPaint setShader

List of usage examples for android.text TextPaint setShader

Introduction

In this page you can find the example usage for android.text TextPaint setShader.

Prototype

public Shader setShader(Shader shader) 

Source Link

Document

Set or clear the shader object.

Usage

From source file:Main.java

/**
 * Draw text on canvas. Shade if text too long to fit.
 *
 * @param canvas The canvas to draw in.// w ww  . ja v  a2 s.  c o  m
 * @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);
}