如何配置图表自定义标签的图像

时间:2016-06-27 09:07:44

标签: c# charts

我想用背景图片替换c#图表上的自定义标签,然后在上面写上标签文字。

我尝试使用图片标签属性&但是所有这些都是将它们放在一起。

这可能吗?图表可以通过y co-ords所以我可以使用绘制函数吗?

enter image description here enter image description here

由于

1 个答案:

答案 0 :(得分:2)

以下是动态创建图表图像的示例。您将需要根据需要使用不同的文本和不同的名称创建它们。::

Image img = Image.FromFile(someTemplateImage);

// draw a text into it:
using (Graphics G = Graphics.FromImage(img))
    G.DrawString("Hello", Font, Brushes.Blue, 1, 1);
// add it to the chart images with a name:
chart.Images.Add(new NamedImage("img01", img));

现在我们可以创建一个显示我们图像的自定义标签:

Axis ax = chart.ChartAreas[0].AxisX;
CustomLabel cl = new CustomLabel();
cl.FromPosition = chart.Series[0].Points[0].XValue;  // some values, which will place 
cl.ToPosition = chart.Series[0].Points[1].XValue;    // the cl between two points
cl.Text = "";   // no text, please!

cl.Image = "img01";  // this is our NamedImage

ax.CustomLabels.Add(cl);  // now we can add the CL

当然,使用字体和aligmnment绘制字符串的样式取决于你..

这只是单个图片和单个 cl的示例。根据您的需要,您需要考虑一种命名图像和添加文本的方案。

您可能需要查看帖子以查看移动相关示例:Here我动态创建了大量标记图像,here标记图像用于创建热图。< / p>

这是一个装饰函数,可以将模板图像添加到轴上的每个自定义标签上。:

public void AddornCLs(Chart chart, Axis axis, Image template, Font font, Color color)
{
    Rectangle rect = new Rectangle(Point.Empty, template.Size);
    TextFormatFlags format = TextFormatFlags.HorizontalCenter 
                           | TextFormatFlags.VerticalCenter;

    foreach(CustomLabel cl in axis.CustomLabels)
    {
        string text = cl.Text;
        if (text == "") text = cl.Tag.ToString(); else cl.Tag = cl.Text;
        cl.Text = "";
        if (cl.Name == "") cl.Name = axis.CustomLabels.IndexOf(cl).ToString("CL000");
        Image img = (Image)template.Clone();
        using (Graphics G = Graphics.FromImage(img))
            TextRenderer.DrawText(G, text, font, rect, color, format);
        chart.Images.Add(new NamedImage(cl.Name, img));
        cl.Image = cl.Name;
    }
}