0

我正在创建一个带有面板(System.Windows.Forms.Panel)的 UI,它将包含一个矩形/椭圆,并且形状的大小(宽度/高度)取决于水平和垂直滑块。下面的代码确实在某种程度上实现了所需的行为。但是,代表面板中心的线条没有样式可以正常工作,而样式DashDotDash导致在面板的对角线和侧面绘制线条而不是指定的点(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- ShapeContainers/RectangleShape/EllipseShape 而不是使用 WinForms.Panel?

4

1 回答 1

0

这应该是对的:

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 一起工作。或者你可以忽略它们,正如 Hans 指出的那样,可能在这个简单的应用程序中它不会导致任何减速。

于 2013-07-30T19:09:42.173 回答