如何在Form的中间绘制一个圆,如何找到圆的中心?

Dan*_*Lip 3 c# winforms

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
    {
        int x1, x2, wid = 100;

        public Form1()
        {
            InitializeComponent();

            x1 = this.Width / 2 ;
            x2 = this.Height / 2 ;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {


            e.Graphics.DrawEllipse(Pens.Red, x1,x2, wid, wid);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在表单中间绘制一个简单的圆,然后再绘制从圆心出来的线。我该怎么做 ?

Bra*_*rad 5

属性this.Widththis.Height并与this.Bounds描述自身的相同:

获取或设置控件的大小和位置,包括其相对于父控件的非客户端元素(以像素为单位)

这意味着您需要调整边框和标题栏的粗细。使用this.ClientRectangle避免了整个问题。

public partial class Form1 : Form
{
    int circleDiameter  = 100;

    public Form1()
    {
        InitializeComponent();
    }

     private void Form1_Paint(object sender, PaintEventArgs e)
    {

        Point CenterPoint = new Point()
        {
            X = this.ClientRectangle.Width/2,
            Y = this.ClientRectangle.Height/2
        };
        Point topLeft = new Point()
        {
            X=(this.ClientRectangle.Width - circleDiameter) / 2,
            Y=(this.ClientRectangle.Height - circleDiameter) / 2
        };
        Point topRight = new Point()
        {
            X=(this.ClientRectangle.Width + circleDiameter) / 2,
            Y=(this.ClientRectangle.Height - circleDiameter) / 2
        };
        Point bottomLeft = new Point()
        {
            X=(this.ClientRectangle.Width - circleDiameter) / 2,
            Y=(this.ClientRectangle.Height + circleDiameter) / 2
        };
        Point bottomRight = new Point()
        {
            X=(this.ClientRectangle.Width + circleDiameter) / 2,
            Y=(this.ClientRectangle.Height + circleDiameter) / 2
        };

         e.Graphics.DrawRectangle(Pens.Red, topLeft.X, topLeft.Y, circleDiameter, circleDiameter);
         e.Graphics.DrawLine(Pens.Red, CenterPoint, topLeft);
         e.Graphics.DrawLine(Pens.Red, CenterPoint, topRight);
         e.Graphics.DrawLine(Pens.Red, CenterPoint, bottomLeft);
         e.Graphics.DrawLine(Pens.Red, CenterPoint, bottomRight);
    }

    private void Form1_Resize(object sender, EventArgs e)
    {
        this.Invalidate();
    }

}
Run Code Online (Sandbox Code Playgroud)