ASE Home Page Products Download Purchase Support About ASE
ChartDirector Support
Forum HomeForum Home   SearchSearch

Message ListMessage List     Post MessagePost Message

  How to show the chart legend in one single line
Posted by moses on Jan-29-2024 21:32
I want to show the legend box in one single line, if there are many legend items, I want to show only one line and ignore others.
I use the function pChart->addLegend(legendRect.x, legendRect.y, false, cTextBoxFont.strFontName, cTextBoxFont.nSize) to create the legend and the function legend->setHeight(legendRect.nHeight) to set height for the legend, but it doesn't work.

  Re: How to show the chart legend in one single line
Posted by Peter Kwan on Jan-30-2024 22:39
Hi Moses,

You can use Layer.setLegendOrder to disable automatic legend entries for a layer. However, for your case, I assume you cannot determine how many legend entries to keep to ensure they fit on one line.

After some thoughts, I think you can draw the legend entries with your own code. Some of our sample code use this method. One example is as follows:

https://www.advsofteng.com/doc/cdcpp.htm#tracklegend.htm

For your case, we just need to keep the part that draws the legend entries, and I come up with the following subroutine:


std::string getLegendText(XYChart* c)
{
    std::string legendText;

    // Iterate through all layers to build the legend array
    for (int i = 0; i < c->getLayerCount(); ++i) {
        Layer* layer = c->getLayerByZ(i);

        // Iterate through all the data sets in the layer
        for (int j = 0; j < layer->getDataSetCount(); ++j) {
            DataSet* dataSet = layer->getDataSetByZ(j);

            // We are only interested in visible data sets with names
            const char* dataName = dataSet->getDataName();
            int color = dataSet->getDataColor();
            if (dataName && *dataName && (color != Chart::Transparent)) {
                std::string legendEntry = std::string("<*block*>") + dataSet->getLegendIcon() + dataName + "<*/*>";
                if (!legendText.empty())
                    legendText = "        " + legendText;
                legendText = legendEntry + legendText;
            }
        }
    }

    return legendText;
}


It can be used as follows:

... Build the chart as usual, without adding a legend box ...

// Get the legend entries as a CDML text string
std::string legendText = getLegendText(c);

// Add the legend text to the chart as a TextBox
TextBox* myLegendBox = c->addText(legendRect.x, legendRect.y, legendText.c_str(), cTextBoxFont.strFontName, cTextBoxFont.nSize);

// Limit the length to maxWidth, and limit the line to 1 line
myLegendBox->setTruncate(maxWidth, 1);

... You can use Box::setBackground to configure the background and border colors of the TextBox. ...


Best Regards
Peter Kwan