0

I would like to replace the custom labels on c# chart with a background image and then write the label text over it.

I tried using the image label property & text but all that does is place them next to each other.

Is this possible? Can the chart pass the y co-ords so I maybe use a drawn function?

enter image description here enter image description here

Thanks

TaW
  • 53,122
  • 8
  • 69
  • 111
Studley
  • 63
  • 8
  • Can you show an example of what you want it to look? You can simply create images dynamically combining a bitmap and text you draw onto it.. – TaW Jun 27 '16 at 09:31

1 Answers1

2

Here is an example of creating chart images dynamically. You will want to create as many of them as you need with different texts and different names..:

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));

Now we can create a Custom Label that shows our image:

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

Of course styling the drawn string with fonts and aligmnment is up to you..

This is just an example with a single image and a single cl. Depending on your need you will want to think of a scheme for naming the images and adding their texts..

You may want to look into there posts to see move involved examples: Here I create a large number of marker images on the fly and here the markerimages are used to create a heat map.

Here is an adorner function that adds a template image to each custom label on an axis..:

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;
    }
}
Community
  • 1
  • 1
TaW
  • 53,122
  • 8
  • 69
  • 111