Android - 如何在屏幕中显示图表标题

时间:2012-12-07 10:49:17

标签: android achartengine

我正在使用achartengine来显示折线图。我的图表标题过于冗长。因为有些文字超出了屏幕。现在我想把它放在屏幕宽度上(是否可以在多行中设置它?)。我试过但是我没有得到。谁能帮我。

参考图片 enter image description here

1 个答案:

答案 0 :(得分: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...)
}