Home > Mobile >  How do I calculate if a box is located more in the upper part of a window or in the lower?
How do I calculate if a box is located more in the upper part of a window or in the lower?

Time:02-18

With my eyes, I can immediately determine if an object is located in the upper half of a box or in the lower half.

enter image description here

One will right away say that the white box is located in the lower part of the blue box.

But how can I calculate that in an efficient way?

Would I split the blue box in an uppper and lower half and then create intersecting rects for the white box and both parts and then have a look which intersecting rect is the one with the most volume?

Thank you!

Thank you!

CodePudding user response:

Your approach is good and best yet, the Windows API can help us out. The code is simpler than writing all the needed comparisons yourself.

Private Type RECT
   Left As Long
   Top As Long
   Right As Long
   Bottom As Long
End Type

Private Declare Function SetRect Lib "user32" (lpRect As RECT, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Private Declare Function IntersectRect Lib "user32" (lpDestRect As RECT, lpSrc1Rect As RECT, lpSrc2Rect As RECT) As Long

Private Sub Command1_Click()
   Dim UpperArea As RECT
   Dim LowerArea As RECT
   Dim WhiteBox As RECT
   Dim IntersectUpper As RECT
   Dim IntersectLower As RECT

   'define rectangles for upper area, lower area, and the white box
   SetRect UpperArea, Frame1.Left, Frame1.Top, Frame1.Left   Frame1.Width, Frame1.Top   (Frame1.Height * 0.5)
   SetRect LowerArea, Frame1.Left, Frame1.Top   (Frame1.Height * 0.5), Frame1.Left   Frame1.Width, Frame1.Top   Frame1.Height
   SetRect WhiteBox, Frame2.Left, Frame2.Top, Frame2.Left   Frame2.Width, Frame2.Top   Frame2.Height

   'check where the white box is located
   If IntersectRect(IntersectUpper, UpperArea, WhiteBox) > 0 Or IntersectRect(IntersectLower, LowerArea, WhiteBox) > 0 Then
      If IntersectUpper.Bottom - IntersectUpper.Top > IntersectLower.Bottom - IntersectLower.Top Then
         MsgBox "More in the upper"
      Else
         MsgBox "More in the lower"
      End If
   Else
      MsgBox "Outside the box"
   End If
End Sub
  • Related