List of usage examples for android.text TextPaint breakText
public int breakText(String text, boolean measureForwards, float maxWidth, float[] measuredWidth)
From source file:Main.java
/** * Draw text on canvas. Shade if text too long to fit. * * @param canvas The canvas to draw in./*from www .j a va2s .com*/ * @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); }