2012-12-19 42 views
1

我在使用System.Web.UI.DataVisualization.Charting在我的應用程序中構建圖表。 我需要某些文本元素(例如圖例)來包含上標文本。如何在MS Chart中顯示上標文本?

我該怎麼做?

到目前爲止,我已經嘗試過使用HTML標記,但它不能識別它們 - 標記按原樣顯示。我也無法找到任何bool屬性來允許HTML格式的字符串。

回答

1

不幸的是,沒有任何內置函數。
唯一的辦法是處理PostPaint事件並使用一些支持複雜格式的渲染器繪製自己的文本。

例如,您可以使用能夠在Graphics對象上繪製html的HtmlRenderer

下面是使用的例子:

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

,這裏是結果的快照:

enter image description here