-2

你好我写的代码给出了驱动器列表、容量和可用大小。我想根据每个驱动器的大小绘制饼图,如下所示:

驱动空间饼图

这是我到目前为止的代码 - 大小值在 freeSize 和 fullSize 变量中

string[] drivers = new string[5];
int freeSize;
int fullSize;

private void Form1_Load(object sender, EventArgs e)
{

    foreach (var item in System.IO.Directory.GetLogicalDrives())
    {
        int i = 0;
        drivers[i] = item;

        comboBox1.Items.Add(drivers[i]);
        ++i;
    }
}

private void btnSorgula_Click(object sender, EventArgs e)
{

    string a = comboBox1.Items[comboBox1.SelectedIndex].ToString();
    System.IO.DriveInfo di = new System.IO.DriveInfo(a);
    if (!di.IsReady)
    {
        MessageBox.Show("not ready");
        return;
    }
    decimal freeByt= Convert.ToDecimal(di.TotalFreeSpace);
    decimal freeGb = freeByt / (1024 * 1024*1024);
    label1.Text = freeGb.ToString();
    freeSize = Convert.ToInt32(freeGb);

    decimal totalByt = Convert.ToDecimal(di.TotalSize);
    decimal tottalGb = totalByt / (1024 * 1024 * 1024);
    label2.Text = Convert.ToString(tottalGb);
    fullSize = Convert.ToInt32(tottalGb);
}


private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Rectangle rect = new Rectangle(10, 10, 100, 100);
    g.FillPie(Brushes.Black, rect, fullSize, fullSize / freeSize);
    g.FillPie(Brushes.RoyalBlue, rect, 140, 100);
}
4

2 回答 2

0

这个怎么样:

private Image GetCake(int width, int height, double percentage)
{
    var bitmap = new Bitmap(width, height);

    using (var g = Graphics.FromImage(bitmap))
    {
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        g.FillEllipse(Brushes.DarkMagenta, 1, 9, width - 2, height - 10);
        g.DrawEllipse(Pens.Black, 1, 9, width - 2, height - 10);
        g.FillPie(Brushes.DarkBlue, 1, 9, width - 2, height - 10, 0, (int)(360 * percentage));
        g.DrawPie(Pens.Black, 1, 9, width - 2, height - 10, 0, (int)(360 * percentage));

        g.FillEllipse(Brushes.Magenta, 1, 1, width - 2, height - 10);
        g.DrawEllipse(Pens.Black, 1, 1, width - 2, height - 10);
        g.FillPie(Brushes.Blue, 1, 1, width - 2, height - 10, 0, (int)(360 * percentage));
        g.DrawPie(Pens.Black, 1, 1, width - 2, height - 10, 0, (int)(360 * percentage));
        g.DrawArc(Pens.Blue, 1, 1, width - 2, height - 10, 0, (int)(360 * percentage));
    }

    return bitmap;
}

你可以这样称呼它:

myPictureBox.Image = GetCake(myPictureBox.Width, myPictureBox.Height, 0.4);

意思是0.440%。所以填写 0 到 1 之间的任何值来设置所需的百分比。

于 2012-09-11T11:23:38.137 回答
0

您的代码的问题是Form1_Paint在绘制表单时调用它,例如在第一次显示时启动之后。在那个时间点,该按钮尚未被点击,freeSize因此为 0。

要解决此问题,请更改代码,使其仅在至少单击一次按钮时才绘制。

于 2012-09-11T11:23:43.660 回答