动态形状图形c#

Dynamic shape graphic c#

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

这是我的主要代码。其他 类 如圆形、方形和三角形也存在。

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();
    }

您应该像这样使用 PanelPaint 事件:

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 活动!!