5

I have a View which draws a rectangle with a line of text inside of it. The view uses break text to ensure that no text extends outside of the rectangle; it ignores any text that does. This works fine for some characters, but often Strings made up of 'l's and 'f's extend outside of the rectangle. So, I'm in need of a sanity check here: Is there some obvious flaw in my below code, or is it possible that Paint.breakText(...) is inaccurate?

public void onDraw(Canvas canvas)
{
    int MARGIN = 1;
    int BORDER_WIDTH = 1;

    Paint p = new Paint();
    p.setAntiAlias(true);
    p.setTextSize(12);
    p.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));

    RectF rect = getRect();

    float maxWidth = rect.width() - MARGIN - BORDER_WIDTH * 2;

    String str = getText();
    char[] chars = str.toCharArray();
    int nextPos = p.breakText(chars, 0, chars.length, maxWidth, null);
    str = str.substring(0, nextPos);

    float textX = MARGIN + BORDER_WIDTH;
    float textY = (float) (Math.abs(p.getFontMetrics().ascent) + BORDER_WIDTH + MARGIN);

    canvas.drawText(str, textX, textY, p);

    p.setStrokeWidth(BORDER_WIDTH);
    p.setStyle(Style.STROKE);

    canvas.drawRect(rect, p);
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
ab11
  • 19,770
  • 42
  • 120
  • 207

2 Answers2

10

This was fixed by: Paint.setSubpixelText(true);

ab11
  • 19,770
  • 42
  • 120
  • 207
0

The problem might be how you draw your rectangle. Strokes are not outside of the rectangle, half of the stroke is inside, half is outside.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • I doubt this is the issue. The given code assumes that the entire stroke is inside the rectangle (this is taken into account with by the "maxWidth", "textX", and "textY" variables). So, if anything, the text should be likely to break earlier than expected, but should never extend outside of the rectangle. – ab11 Feb 25 '11 at 18:41
  • The problem was that fractional metrics (sub pixel text) were not set. – ab11 Mar 01 '11 at 15:28