You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++版ChartDirector的XY图表自定义位置添加标签

在C++版ChartDirector XY图表自定义位置添加标签的解决方案

要在绘图区指定像素位置添加自定义标签,可利用ChartDirector的addText方法,结合绘图区位置坐标计算标签的绝对位置,具体实现如下:

修改后的完整代码

// Create a XYChart object of size 740 x 760 pixels
XYChart* c = new XYChart(740, 760);

// Set the plotarea at (45, 25) and of size 680 x 680 pixels, with a light grey border
// (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey color (0xc0c0c0)
c->setPlotArea(45, 25, 680, 680, -1, -1, 0xc0c0c0, 0xc0c0c0, -1);

// Add a title to the chart using 18pt Times Bold Itatic font.
c->addTitle("X-Y Scatter Plot", "timesbi.ttf", 10);

// Add a title to the y axis using 12pt Arial Bold Italic font
c->yAxis()->setTitle("Y Distance (m)", "arialbi.ttf", 8);

// Add a title to the x axis using 12pt Arial Bold Italic font
c->xAxis()->setTitle("X Distance (m)", "arialbi.ttf", 8);

// Set the axes line width to 3 pixels
c->xAxis()->setWidth(2);
c->yAxis()->setWidth(2);

// Set the x and y axis to scale 
c->xAxis()->setLinearScale((set_xy_range + margin_distance) * (-1), set_xy_range + margin_distance, set_xy_range_r);
c->yAxis()->setLinearScale((set_xy_range + margin_distance) * (-1), set_xy_range + margin_distance, set_xy_range_r);

// --- 新增代码:添加自定义位置标签 ---
// 获取绘图区对象,用于计算绝对坐标
PlotArea* plotArea = c->getPlotArea();
// 转换绘图区内部相对位置(20,40)为图表绝对像素坐标
int labelX = plotArea->getLeft() + 20;
int labelY = plotArea->getTop() + 40;
// 添加数字标签,示例内容为"123",可替换为目标数值或文本
TextBox* customLabel = c->addText(labelX, labelY, "123", "arial.ttf", 10);
// 可选:设置标签样式,比如红色字体、浅黄背景带灰色边框
customLabel->setFontColor(0xff0000);
customLabel->setBackground(0xffffee, 0xcccccc);
// --- 新增代码结束 ---

XYChartView.setChart(c);

关键说明

  • 若需基于数据坐标(而非绘图区像素坐标)添加标签,直接使用addText重载方法:c->addText(dataX, dataY, "标签内容"),ChartDirector会自动完成数据坐标到像素坐标的转换
  • 可通过TextBox类的方法调整标签对齐方式、旋转角度等样式,例如customLabel->setAlignment(Left)设置左对齐

内容的提问来源于stack exchange,提问作者lei lei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:45:16