Windows窗体中的DashDot/Dash样式绘制错误,面板与形状容器
本文关键字:错误 绘制 窗体 DashDot 样式 Dash Windows | 更新日期: 2023-09-27 18:25:43
我正在创建一个带有面板(System.Windows.Forms.Panel
)的UI,该面板将包含矩形/椭圆,形状的大小(宽度/高度)取决于水平和垂直滑块。下面的代码确实在某种程度上实现了所需的行为。但是,表示没有样式的嵌板中心的线可以很好地工作,而DashDot
或Dash
的样式会导致在嵌板的对角线和边上绘制线,而不是指定的点(startPoint、endPoint)。有没有办法根据面板的大小将矩形居中?
private void vScroll_Scroll(object sender, ScrollEventArgs e)
{
this.vScrollValue.Text = vScrollBar.Value.ToString();
panel.Invalidate(/*myRectangle*/);
}
private void hScrollBar_Scroll(object sender, ScrollEventArgs e)
{
this.hScrollValue.Text = hScrollBar.Value.ToString();
panel.Invalidate(/*myRectangle*/);
}
private void panel_Paint(object sender, PaintEventArgs e)
{
myRectangle = new Rectangle(90, 90, hScrollBar.Value, vScrollBar.Value);
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat("panel.Location.X = {0} panel.Location.Y = {1} (panel.Size.Height/2) = {2}", panel.Location.X, panel.Location.Y, e.ClipRectangle);
//MessageBox.Show(messageBoxCS.ToString(), "Panel Paint");
//Panel's midpoint (location(x,y) = 88,44, Size(x,y) = 182,184)
Point startPoint = new Point(e.ClipRectangle.Location.X, e.ClipRectangle.Location.Y + (e.ClipRectangle.Size.Height / 2));
Point endPoint = new Point(e.ClipRectangle.Location.X + e.ClipRectangle.Size.Width, e.ClipRectangle.Location.Y + (e.ClipRectangle.Size.Height / 2));
Pen dashRed = Pens.Red;
e.Graphics.DrawRectangle(Pens.Black, myRectangle);
//dashRed.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
e.Graphics.DrawLine(Pens.Red, startPoint, endPoint);
}
在InitializeComponent()
方法中,paintHandler事件注册如下:
this.panel.Paint += new System.Windows.Forms.PaintEventHandler(this.panel_Paint);
此外,作为C#的新手,我应该使用Micorsoft.VisualBasic.Powerpack
-ShapeChannelse/RectangleShape/EllipseShape而不是使用WinForms.Panel吗?
这应该是正确的:
private void panel_Paint(object sender, PaintEventArgs e)
{
myRectangle = new Rectangle(90, 90, hScrollBar.Value, vScrollBar.Value);
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat("panel.Location.X = {0} panel.Location.Y = {1} (panel.Size.Height/2) = {2}", panel.Location.X, panel.Location.Y, e.ClipRectangle);
//MessageBox.Show(messageBoxCS.ToString(), "Panel Paint");
//Panel's midpoint (location(x,y) = 88,44, Size(x,y) = 182,184)
e.Graphics.DrawRectangle(Pens.Black, myRectangle);
if(e.ClipRectangle.Location.Y < this.Size.Height / 2 && e.ClipRectangle.Location.Y + e.ClipRectangle.Size.Height > this.Size.Height / 2)
{
Point startPoint = new Point(e.ClipRectangle.Location.X, this.Size.Height / 2);
Point endPoint = new Point(e.ClipRectangle.Location.X + e.ClipRectangle.Size.Width, this.Size.Height / 2);
Pen dashRed = Pens.Red;
dashRed.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
e.Graphics.DrawLine(dashRed, startPoint, endPoint);
}
}
这应该是如何使它与ClipRectangle一起工作。或者你可以忽略它们,正如汉斯所指出的,也许在这个简单的应用程序中,它不会导致任何速度减慢。