0

我正在使用 achartengine 来显示折线图。我的图表标题太长了。因此,一些文本超出了屏幕范围。现在我想把它适应屏幕宽度(是否可以将它设置为多行?)。我试过但我没有。谁能帮我。

参考图片 在此处输入图像描述

4

1 回答 1

0

首先也是最简单的方法是在标题中添加换行符First line\nSecond line

第二种方法是修改 achart 的源。课堂上有drawString方法AbstractChart。我不知道它是否绘制图形标题,但它会让您了解它是如何完成的。

/**
 * Draw a multiple lines string.
 * 
 * @param canvas the canvas to paint to
 * @param text the text to be painted
 * @param x the x value of the area to draw to
 * @param y the y value of the area to draw to
 * @param paint the paint to be used for drawing
 */
protected void drawString(Canvas canvas, String text, float x, float y, Paint paint) {
    String[] lines = text.split("\n");
    Rect rect = new Rect();
    int yOff = 0;
    for (int i = 0; i < lines.length; ++i) {
        canvas.drawText(lines[i], x, y + yOff, paint);
        paint.getTextBounds(lines[i], 0, lines[i].length(), rect);
        yOff = yOff + rect.height() + 5; // space between lines is 5
    }
}

您必须确定需要多少行。我们可以用paint的measureText(String)方法来测量文本的宽度。然后,如果文本宽度大于可用宽度,则将文本分成两行。

if (paint.measureText(text) > canvas.getWidth()) {
    ... // Split text in two lines
        // For example you can do following steps
        // 1. Find last position of space with `text.lastIndesOf(' ')`.
        // 2. Then take substring from beginning of text to found last position of space.
        // 3. Try again with `paint.measureText` if substing fits in available width.
        // 4. In case it fits - insert line break instead of space, if not start again from 1. (find location of pre-last space, get substring from start to found location, check if it fits and so on...)
}
于 2012-12-07T11:47:02.220 回答