C# 如何绘制驱动器容量的图形
您好,我写的代码给出了驱动器列表、容量和驱动器的自由大小。我想根据每个驱动器的大小绘制饼图,如下所示: 这是我到目前为止的代码-大小值在freeSize和fullSize变量中C# 如何绘制驱动器容量的图形,c#,graphics,C#,Graphics,您好,我写的代码给出了驱动器列表、容量和驱动器的自由大小。我想根据每个驱动器的大小绘制饼图,如下所示: 这是我到目前为止的代码-大小值在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.Directo
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);
}
这个怎么样:
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之间的任何值,以设置所需的百分比。代码的问题是,每次绘制表单时都会调用Form1\u Paint
,例如,在启动后第一次显示表单时。此时按钮尚未单击,因此释放大小
为0
若要解决此问题,请更改代码,使其仅在按钮至少单击一次后才绘制。!它不起作用,但表示发生了DividedByzero异常