简体   繁体   English

.NET饼图:如何向切片添加文本和旋转图表

[英].NET pie chart: how to add text to slices and rotate chart

The code below creates a 24 slice pie chart. 下面的代码创建了一个24切片饼图。 How do I: 我如何:

  1. Add text labels to each slice a la "Wheel of Fortune". 在“财富之轮”中为每个切片添加文本标签。
  2. Rotate the pie chart? 旋转饼图? I want it to spin like "Wheel of Fortune". 我希望它像“财富之轮”一样旋转。

     private void DrawPieChart() { Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); Rectangle rect = new Rectangle(0, 0, 300, 300); float angle = 0; Random random = new Random(); int sectors = 24; int sweep = 360 / sectors; for(int i=0; i<24;i++) { Color clr = Color.FromArgb(random.Next(0, 255),random.Next(0, 255), random.Next(0, 255)); g.FillPie(new SolidBrush(clr), rect, angle, sweep); angle += sweep; } g.Dispose(); } 

To add text labels, call g.DrawString . 要添加文本标签,请调用g.DrawString

EDIT : To make the textvertical like your image, rotate the Graphics object to angle + sweep / 2 , and draw your text. 编辑 :要使textvertical像图像一样,将Graphics对象旋转到angle + sweep / 2 ,然后绘制文本。 To make it draw downward, yopu may be able to draw it in a small width and rely on character wrapping; 为了使它向下绘制,yopu可能能够以较小的宽度绘制它并依靠字符包裹; if that doesn't work, draw it character vy chaaracter and use g.MeasureString to figure out where to put the next character. 如果这不起作用,绘制字符vy chaaracter并使用g.MeasureString来确定下一个字符的放置位置。

To rotate the entire chart, call g.RotateTransform with an angle in degrees before drawing it. 要旋转整个图表,请在绘制之前以度数角度调用g.RotateTransform EDIT : like this: 编辑 :像这样:

    private void DrawPieChart()
    {
        Graphics g = this.CreateGraphics();
        g.Clear(this.BackColor);
        Rectangle rect = new Rectangle(0, 0, 300, 300);
        float angle = 0;
        Random random = new Random();
        int sectors = 24;
        int sweep = 360 / sectors;

         g.RotateTransform(90);        //Rotates by 90 degrees
         for(int i=0; i<24;i++)
        {
            Color clr = Color.FromArgb(random.Next(0, 255),random.Next(0, 255), random.Next(0, 255));
            g.FillPie(new SolidBrush(clr), rect, angle, sweep);
            angle += sweep;
        }
        g.Dispose();
    }

TO animate the rotation, make a field for the angle, increment it on a timer, and pass the field to g.RotateTransform . 要为旋转设置动画,请为角度创建一个字段,在计时器上增加该字段,然后将该字段传递给g.RotateTransform

Also, the correct way to draw things is to handle the control's Paint event, and draw using e.Graphics . 另外,绘制事物的正确方法是处理控件的Paint事件,并使用e.Graphics Then, when you want to redraw it, call Invalidate . 然后,当您想重绘它时,请调用Invalidate To prevent flickering, call this.SetStyle(ControlStyles.DoubleBuffer, true); 要防止闪烁,请调用this.SetStyle(ControlStyles.DoubleBuffer, true); in the constructor. 在构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM