以不同的分辨率捕获相同的像素矩形

时间:2019-06-02 17:29:31

标签: vb.net

无论当前选择的监视器的分辨率是多少,我都试图捕获相同的像素矩形区域。我有一些代码可以捕获我需要的区域(1920x1080、2560x1440),但是我目前正在对所需区域的起点/终点进行硬编码。我知道有一个更好的方法来执行此操作,因为我目前的方法很草率,并且仅适用于两种分辨率。关于方法有什么建议吗?

If Screen.AllScreens(intMonitorSelected).Bounds.Height = "1080" Then
    StartX = Screen.AllScreens(intMonitorSelected).Bounds.Left + TenStartX
    EndX = Screen.AllScreens(intMonitorSelected).Bounds.Left - StartX + TenEndX
    StartY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - TenStartY
    EndY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - StartY - TenEndY
ElseIf Screen.AllScreens(intMonitorSelected).Bounds.Height = "1440" Then
    StartX = Screen.AllScreens(intMonitorSelected).Bounds.Left + FourteenStartX
    EndX = Screen.AllScreens(intMonitorSelected).Bounds.Left - StartX + FourteenEndX
    StartY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - FourteenStartY
    EndY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - StartY - FourteenEndY
End If
        Dim screenshot As System.Drawing.Bitmap
        Dim graph As Graphics
        Dim bounds As New Rectangle(StartX, StartY, EndX, EndY)

        screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
        graph = Graphics.FromImage(screenshot)
        graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)

        Return New Bitmap(screenshot)

致电:

Test.Image = GetImage(48, 210, 53, 35, 63, 220, 70, 47)

如您所见,正确的像素起点和终点根据分辨率而略有不同。我还需要扩展它以便能够在任何分辨率下工作。我很困惑; /

1 个答案:

答案 0 :(得分:0)

弄清楚了,现在只需要弄清楚调整矩形以缩小/增长的数学方法即可。

        Dim OCoordx = "65"
        Dim OCoordy = "1369"

        Dim posX As Long = OCoordx / 2560 * Screen.AllScreens(intMonitorSelected).Bounds.Width
        Dim posY As Long = OCoordy / 1440 * Screen.AllScreens(intMonitorSelected).Bounds.Height

        posX = Screen.AllScreens(intMonitorSelected).Bounds.Left + posX
        posY = Screen.AllScreens(intMonitorSelected).Bounds.Top + posY