Reputation: 5891
I'm building charts in my application using System.Web.UI.DataVisualization.Charting
.
I need certain text elements, such as Legends, to contain superscripted text.
How can I do this?
So far I've tried using HTML tags, but it doesn't recognize them - the tags are displayed as-is. I'm also unable to find any bool
property to allow HTML formatted strings.
Upvotes: 1
Views: 674
Reputation: 57220
Unfortunately, there isn't any built-in function.
The only way is to handle the PostPaint event and draw your own text using some renderer supporting complex formatting.
For example you could use HtmlRenderer that is able to draw html on Graphics objects.
Here's an example of usage:
public Form1()
{
InitializeComponent();
// subrscribe PostPaint event
this.chart1.PostPaint += new EventHandler<ChartPaintEventArgs>(chart1_PostPaint);
// fill the chart with fake data
var values = Enumerable.Range(0, 10).Select(x => new { X = x, Y = x }).ToList();
this.chart1.Series.Clear();
this.chart1.DataSource = values;
// series name will be replaced
var series = this.chart1.Series.Add("SERIES NAME");
series.XValueMember = "X";
series.YValueMembers = "Y";
}
void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
var cell = e.ChartElement as LegendCell;
if (cell != null && cell.CellType == LegendCellType.Text)
{
// get coordinate of cell rectangle
var rect = e.ChartGraphics.GetAbsoluteRectangle(e.Position.ToRectangleF());
var topLeftCorner = new PointF(rect.Left, rect.Top);
var size = new SizeF(rect.Width, rect.Height);
// clear the original text by coloring the rectangle (yellow just to highlight it...)
e.ChartGraphics.Graphics.FillRectangle(Brushes.Yellow, rect);
// prepare html text (font family and size copied from Form.Font)
string html = string.Format(System.Globalization.CultureInfo.InvariantCulture,
"<div style=\"font-family:{0}; font-size:{1}pt;\">Series <sup>AAA</sup></div>",
this.Font.FontFamily.Name,
this.Font.SizeInPoints);
// call html renderer
HtmlRenderer.HtmlRender.Render(e.ChartGraphics.Graphics, html, topLeftCorner, size);
}
}
and here's a snapshot of the result:
Upvotes: 1