在C#中绘制相对线
伙计们,我知道这将是一个简单的答案,但我似乎无法弄清楚。我有一个正在尝试构建的 C# Winform 应用程序。我正在尝试在表单底部上方 60 像素处绘制一条白线。我正在使用这段代码:
private void MainForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(Pens.White, 10, this.Height-60, 505, this.Height-60);
}
足够简单,但是没有画线。经过一番调试,我发现它正在绘制这条线,但它是在我的表单之外绘制的。如果我将 -60 更改为 -175,那么我可以在表单底部看到它。这将解决我的问题,除了当我的表单高度发生变化时,该线越来越接近我的表单底部,直到最终再次脱离表单。我做错了什么?我使用了错误的图形单元吗?或者我需要进行更复杂的计算才能确定距表单底部 60 像素的距离?
Guys, I know this is going to turn out to be a simple answer, but I can't seem to figure it out. I have a C# Winform application that I am trying to build. I am trying to draw a white line 60 pixels above the bottom of the form. I am using this code:
private void MainForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(Pens.White, 10, this.Height-60, 505, this.Height-60);
}
Simple enough, however no line is drawn. After some debugging, I figured out that it IS drawing the line, but it is drawing it outside my form. If I change the -60 to -175, then I can see it at the bottom of my form. This would solve my problem, except as my form's height changes, the line draws closer and closer to the bottom of my form until eventually, its off the form again. What am I doing wrong? Am I using the wrong graphics unit? Or is there a more complex calculation I need to do to determine 60 pixels from the bottom of my form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
ClientSize.Height
而不是Height
。Height
属性返回整个窗体的高度(包括标题栏和窗口的其他部分)。ClientSize
属性为您提供了可以绘制的区域的大小。有关详细信息,请参阅
ClientSize 属性
。
You need to use
ClientSize.Height
instead ofHeight
. TheHeight
property returns the height of the entire form (including title bar and other parts of the window). TheClientSize
property gives you the size of the area where you can draw.For more information, see
ClientSize
property at MSDN.这段代码在哪里?我注意到它是一个事件处理程序,不一定是 MainForm 的成员。因此,当您引用
this.Height
时,“this”可能不是 MainForm(至少我们无法从您包含的代码片段中看出)。一般来说,最好在 MainForm 中重写 OnPaint,而不是附加事件处理程序。在进行您自己的任何绘制之前,请务必调用基类的 OnPaint。有关详细信息,请参阅 OnPaint在 MSDN。
Where is this code? I noticed that it is an event handler and not necessarily a member of MainForm. So, when you reference
this.Height
, "this" might not be the MainForm (at least we can't tell from the code fragment you've included). In general, it's better to override OnPaint in your MainForm rather than attaching an event handler. Just be sure to call the base class's OnPaint before doing any painting of your own.For more information, see OnPaint at MSDN.