在PictureBox中绘制矩形

时间:2015-03-20 00:52:37

标签: vb.net

我正在构建一个截图程序,我需要能够让用户用鼠标选择屏幕截图的区域。到目前为止,我已经能够从左上角到右下角进行编程,但是我尝试从右上角到左上角的尝试都没有成功。该怎么做?

这是左上角到右下角的工作代码:

If e.X > SelectedPoint.X And e.Y > SelectedPoint.Y Then
            recsize = New Point(e.X - SelectedPoint.X, e.Y - SelectedPoint.Y)
            rectangle = New Rectangle(SelectedPoint, recsize)

以下是完整代码:

If IsMouseDown = True Then
        Screenshot_PicBox.Refresh()
        Dim recsize As Point
        Dim rectangle As Rectangle
        If e.X > SelectedPoint.X And e.Y > SelectedPoint.Y Then
            recsize = New Point(e.X - SelectedPoint.X, e.Y - SelectedPoint.Y)
            rectangle = New Rectangle(SelectedPoint, recsize)
        ElseIf e.X < SelectedPoint.X And e.Y > SelectedPoint.Y Then
            recsize = New Point(e.X - SelectedPoint.X, e.Y - SelectedPoint.Y)
            SelectedPoint = New Point(-SelectedPoint.X, SelectedPoint.Y)
            rectangle = New Rectangle(SelectedPoint, recsize)
        End If
        Screenshot_PicBox.CreateGraphics.DrawRectangle(Pens.Blue, rectangle)
    End If

1 个答案:

答案 0 :(得分:1)

这是一种方式。它不使用Dim recsize As Point但是如果您愿意,可以将其替换回来:

If IsMouseDown = True Then
    Screenshot_PicBox.Refresh()
    Dim rectangle As New Rectangle
            If e.X > SelectedPoint.x Then
                'left to right
                rectangle.Width = e.X - SelectedPoint.x
                rectangle.X = SelectedPoint.x
            Else
                'right to left
                rectangle.Width = SelectedPoint.x - e.X
                rectangle.X = e.X
            End If
            If e.Y > SelectedPoint.Y Then
                'top to bottom
                rectangle.Height = e.Y - SelectedPoint.Y
                rectangle.Y = SelectedPoint.Y
            Else
                'bottom to top
                rectangle.Height = SelectedPoint.Y - e.Y
                rectangle.Y = e.Y
            End If
    Screenshot_PicBox.CreateGraphics.DrawRectangle(Pens.Blue, rectangle)
End If