如何绘制驱动器容量的图形

时间:2012-09-11 09:34:46

标签: c# graphics

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

Drive space pie chart

这是我到目前为止的代码 - 大小值在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);
}

2 个答案:

答案 0 :(得分: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.4表示40%。因此,请填写0到1之间的任何值以设置所需的百分比。

答案 1 :(得分:0)

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

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