动态形状图形c#

时间:2015-02-25 13:11:21

标签: c# graphics windows-forms-designer

我想在面板左上方绘制图形(形状)。将根据所选形状和轨迹栏给出的值绘制形状。轨道条值不是特定的,即不是像素或毫米,所以基本上当轨道条数量增加时,形状应该变大。 enter image description here

这是我的主要代码。其他类如Circle,Square和Triangle也存在。

public partial class drawShape : Form
{

    Graphics drawArea;
    public decimal area;
    double myBoundary = 0;
    double myArea = 0;
    public double length = 100;

    public drawShape()
    {
        InitializeComponent();
        drawArea = pnlDrawArea.CreateGraphics();
    }

    public void updateShape()
    {
        if(rbCircle.Checked)
        {
            drawCircle();
        }

        if(rbSquare.Checked)
        {
            drawSquare();
        }

        if(rbTriangle.Checked)
        {
            drawTriangle();
        }

        if(rb2DecimalPlaces.Checked)
        {
            lblBoundaryLength.Text = myBoundary.ToString("#,0.00");
            lblAreaResult.Text = myArea.ToString("#,0.00");
        }

        if(rb3DecimalPlaces.Checked)
        {
            lblBoundaryLength.Text = myBoundary.ToString("#,0.000");
            lblAreaResult.Text = myArea.ToString("#,0.000");
        }

        if(rb4DecimalPlaces.Checked)
        {
            lblBoundaryLength.Text = myBoundary.ToString("#,0.0000");
            lblAreaResult.Text = myArea.ToString("#,0.0000");
        }
    }

    public void drawCircle()
    {
        Circle myCircle = new Circle(length);
        myArea = myCircle.GetArea(length);
        myBoundary = myCircle.GetCircumference();
        lblAreaResult.Text = myArea.ToString();
        lblBoundaryLength.Text = myBoundary.ToString();
    }

    public void drawSquare()
    {
        Square mySquare = new Square(length);
        myArea = mySquare.GetArea();
        myBoundary = mySquare.GetBoundLength(length);
        lblAreaResult.Text = myArea.ToString();
        lblBoundaryLength.Text = myBoundary.ToString();
    }

    public void drawTriangle()
    {
        Triangle myTriangle = new Triangle(length);
        myArea = myTriangle.GetArea();
        myBoundary = myTriangle.GetBoundLength();
        lblAreaResult.Text = myArea.ToString();
        lblBoundaryLength.Text = myBoundary.ToString();
    }

1 个答案:

答案 0 :(得分:3)

您应该使用Panel Paint这样的事件:

private void pnlDrawArea_Paint(object sender, PaintEventArgs e)
{
        int offset = 20;
        Rectangle bounding = new Rectangle(offset, offset, 
                            (int)myBoundary.Value, (int)myBoundary.Value);

        if (rbSquare.Checked)
        {
           e.Graphics.DrawRectangle(Pens.Red, bounding);
        }
        else if (rbCircle.Checked)
        {
           e.Graphics.DrawEllipse(Pens.Red, bounding);
        }
        // else if...

}

并在updateShape中通过编码简单地调用Paint事件:pnlDrawArea.Invalidate();

对于三角形,你将

  • 使用DrawLines方法和
  • 必须为它计算三个Points
  • 将它们添加到数组或列表中。

不要忘记挂钩Paint事件!!