저는 C#을 배우고 있으며 책에서 연습의 일부로 양식 안에 레이블을 가운데에 넣어야합니다. 양식이 꽤 큰지 아닌지는 중요하지 않습니다. 나는 다른 곳에서 다른 해결책을 찾았고 stackoverflow에서 찾았다. 그리고 나는 그것을 두 가지로 좁혔다. 그러나 꽤 인기있는 솔루션 임에도 불구하고 동일한 결과를 얻지 못하는 것으로 보입니다.양식 내의 컨트롤을 중앙에 놓기
그것은 1
myLabel.Left = (this.ClientSize.Width - myLabel.Width)/2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height)/2;
라벨을 생성한다 약간 좌측면 위로 중심으로부터 오프셋으로 중심이 방법 2
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
그것을 만들 것이다 방법 같다 형태의 중간에 완벽하게 정렬됩니다.
지금, 제 질문은 차이점이 무엇인지, 또는 다른 말로 표현하면 왜 방법 1에서 오프셋 된 채로 남아 있습니까?? 폼의 컨트롤에 추가하기 전에 당신이 라벨의 폭을 사용하고 있기 때문에 이런 일이
//Exercise 16.1
//-------------------
using System.Drawing;
using System.Windows.Forms;
public class frmApp : Form
{
public frmApp(string str)
{
InitializeComponent(str);
}
private void InitializeComponent(string str)
{
this.BackColor = Color.LightGray;
this.Text = str;
//this.FormBorderStyle = FormBorderStyle.Sizable;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.StartPosition = FormStartPosition.CenterScreen;
Label myLabel = new Label();
myLabel.Text = str;
myLabel.ForeColor = Color.Red;
myLabel.AutoSize = true;
myLabel.Left = (this.ClientSize.Width - myLabel.Width)/2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height)/2;
Label myLabel2 = new Label();
myLabel2.Text = str;
myLabel2.ForeColor = Color.Blue;
myLabel2.AutoSize = false;
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(myLabel);
this.Controls.Add(myLabel2);
}
public static void Main()
{
Application.Run(new frmApp("Hello World!"));
}
}
+1 - 저에게 논리적입니다. 초보적인 '차이를 2로 나누기'논리에 약간의 반올림 문제가 있다는 것도 사실이 아닌가? –
@MichaelPerrenoud 필자는 센터링 계산을 충분히 가깝게해야한다고 생각하지만 1 픽셀 씩 나올 수 있습니다. –
예, 맞습니다. 최대 약 1 픽셀이므로 눈에 띄지 않습니다. –