在窗体上绘制一条对角线,在调整窗体大小时重绘

Posted

技术标签:

【中文标题】在窗体上绘制一条对角线,在调整窗体大小时重绘【英文标题】:Draw a diagonal line across form that redraws when the form is resized 【发布时间】:2015-12-22 07:30:06 【问题描述】:

我刚开始使用 GDI - 第一行没问题 - 但第二行...... 我想画一条从 (0,0) 到 (MaxWidth,MaxHeight) 的简单对角线。

这是我的代码:

Public Class Form1
    Dim g As Graphics = Me.CreateGraphics
    Dim stift As New Pen(Brushes.Black, 3)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim x1 = 0, y1 = 0, x2 = Me.Size.Width, y2 = Me.Size.Height
        g.DrawLine(stift, x1, y1, x2, y2)
    End Sub
End Class

但是该行在第一个未更改的表单的 MaxWidth 和 MaxHeight 处结束。 有人知道吗?

【问题讨论】:

摆脱 CreateGraphics 并使用 Paint 事件。此外,使用 ClientSize 作为宽度和高度。 【参考方案1】:

在 Paint() 事件中绘制线条并允许使用 Button 切换的快速示例:

Public Class Form1

    Private x1 As Integer = 0
    Private y1 As Integer = 0
    Private x2 As Integer = 0
    Private y2 As Integer = 0

    Private DrawLine As Boolean = False
    Private stift As New Pen(Brushes.Black, 3)

    Public Sub New()
        InitializeComponent()

        x2 = Me.ClientSize.Width
        y2 = Me.ClientSize.Height
    End Sub

    Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged
        x2 = Me.ClientSize.Width
        y2 = Me.ClientSize.Height
        Me.Refresh()
    End Sub

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
        If DrawLine Then
            Dim g As Graphics = e.Graphics
            g.DrawLine(stift, x1, y1, x2, y2)
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        DrawLine = Not DrawLine
        Me.Refresh()
    End Sub

End Class

这种方法允许您从其他地方更改坐标并调用 Refresh() 来更新屏幕。对于不止一行,请考虑使用包含坐标信息的 List(),然后在 Paint() 事件中对其进行迭代。

【讨论】:

以上是关于在窗体上绘制一条对角线,在调整窗体大小时重绘的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中绘制对角线

如何在 C# windows 窗体中绘制可缩放图像

html5画布在调整大小时重绘

在 Seaborn Jointplot 上绘制对角线(相等线)

窗体背景的绘制(Windows窗体每次都会重绘其窗体背景,所以我们可以通过拦截窗体重绘背景的消息(WM_ERASEBKGND),并自定义方法来实现重绘窗体背景)

如何在表格的某单元格中绘制一条对角线