图片框填充一些百分比

时间:2013-02-07 11:59:33

标签: c# picturebox

我对C sharp编程很新。我的设计如下图所示。

我的概念是我必须在“传输音量”文本框中设置一些音量(例如100),然后按“设置”按钮。它自动设置图片框的比例,工作正常。

现在我想在点击“重新生成”按钮时用颜色填充图片框。要在图片框中填充的颜色百分比应该是TextBox中关于颜色或液体的颜色。

例如,

如果我设置GasPhase = 5;烃类液体= 5;水= 5;油基泥浆= 5;水基泥浆= 5;未识别= 75。

然后图片必须填充75%的“Not Identified”颜色和GasPhase颜色,5%e.t.c。

我写了一些代码,如下所示。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


  namespace test
  {
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    private void txtTransferVolume_TextChanged(object sender, EventArgs e)
    {

    }

    private void txtTransferSet_Click(object sender, EventArgs e)
    {
        string value = txtTransferVolume.Text;
        double midvalue = Convert.ToDouble(value);
        lblTransferBottleMax.Text = value;
        lblTransferBottleMid.Text = (midvalue / 2).ToString();

    }

    private void chkTransferManual_CheckedChanged(object sender, EventArgs e)
    {


    }

    private void btnTransferBottleRegenerate_Click(object sender, EventArgs e)
    {

    }

   }
 }

请帮我填写我想要的内容。

1 个答案:

答案 0 :(得分:1)

这可以通过直接在图片框控件上绘图或在内存中创建位图并在图片框中显示来轻松实现。

示例:

private void DrawPercentages(int[] percentages, Color[] colorsToUse)
{
   // Create a Graphics object to draw on the picturebox
   Graphics G = pictureBox1.CreateGraphics();

   // Calculate the number of pixels per 1 percent
   float pixelsPerPercent = pictureBox1.Height / 100f;

   // Keep track of the height at which to start drawing (starting from the bottom going up)
   int drawHeight = pictureBox1.Height;

   // Loop through all percentages and draw a rectangle for each
   for (int i = 0; i < percentages.Length; i++)
   {
       // Create a brush with the current color
       SolidBrush brush = new SolidBrush(colorsToUse[i]);
       // Update the height at which the next rectangle is drawn.
       drawHeight -= (int)(pixelsPerPercent * percentages[i]);
       // Draw a filled rectangle
       G.FillRectangle(brush, 0, drawHeight, pictureBox1.Width, pixelsPerPercent * percentages[i]);
    }    
}

当然你必须检查两个数组的长度是否相同等等。我只想告诉你如何做到这一点的基本思路。

这是一个如何在数组中获取数据并将其传递给函数的概念。由于您为每个值使用了不同的文本框,因此很难对它们进行迭代,所以现在我正在向您展示如何使用现有的6个值来完成它。

private void btnTransferBottleRegenerate_Click(object sender, EventArgs e)
{
  int[] percentages = new int[6];
  percentages[0] = int.Parse(txtTransferNotIdentified.Text);
  percentages[1] = int.Parse(txtTransferWater.Text);
  // And so on for every textbox

  Color[] colors = new Color[6];
  colors[0] = Color.Red;
  colors[1] = Color.Yellow;
  // And so on for every color

  // Finally, call the method in my example above
  DrawPercentages(percentages, colors);
} 

如果百分比总是不等于100,则可以使用第三个参数指定总和,并在100f方法中将值DrawPercentages更改为此值。