Ruotare un romboide in una DrawingArea

Da Gambas-it.org - Wikipedia.
Versione del 27 lug 2025 alle 22:40 di Vuott (discussione | contributi)
(diff) ← Versione meno recente | Versione attuale (diff) | Versione più recente → (diff)
Vai alla navigazione Vai alla ricerca

Di seguito mostreremo un possibile codice per ruotare un Romboide disegnato in una DrawingArea.

Private DrawingArea1 As DrawingArea
Private Timer1 As Timer
Private rotationAngle As Float = 0  ' angolo in radianti


Public Sub Form_Open()

 With Me
   .Move(0, 0, Screen.AvailableWidth, Screen.AvailableHeight)
   .Arrangement = Arrange.Fill
 End With

 With DrawingArea1 = New DrawingArea(Me) As "DrawingArea1"
   .Background = Color.Lighter(Color.Yellow)
 End With

 Timer1 = New Timer As "Timer1"
 Timer1.Delay = 30    ' circa 33 FPS
 Timer1.Start()

End


Public Sub Timer1_Timer()

 rotationAngle += Rad(1.5)         ' Rotazione di 1.5° per frame
 If rotationAngle >= 2 * Pi Then
   rotationAngle -= 2 * Pi
 End If
 DrawingArea1.Refresh()

End


Public Sub DrawingArea1_Draw()

 Dim cx As Float = DrawingArea1.W / 2
 Dim cy As Float = DrawingArea1.H / 2
' Dimensione del Romboide:
 Dim width As Float = DrawingArea1.W * 0.2
 Dim height As Float = DrawingArea1.H * 0.125

 Dim offset As Float = width * 0.3

 Dim points As New PointF[4]
 Dim i As Integer

' Definisce i 4 vertici del romboide attorno a (0,0)
 points[0] = New PointF(-width / 2 + offset, -height / 2)
 points[1] = New PointF(width / 2 + offset, -height / 2)
 points[2] = New PointF(width / 2 - offset, height / 2)
 points[3] = New PointF(-width / 2 - offset, height / 2)

' Ruota i punti attorno al centro (0,0)
 For i = 0 To 3
   Dim xOld As Float = points[i].X
   Dim yOld As Float = points[i].Y

   points[i].X = xOld * Cos(rotationAngle) - yOld * Sin(rotationAngle)
   points[i].Y = xOld * Sin(rotationAngle) + yOld * Cos(rotationAngle)

' Trasla i punti per centrarli nella DrawingArea
   points[i].X += cx
   points[i].Y += cy
 Next

 With Paint
   .Brush = Paint.Color(Color.Black)
   .LineWidth = 2

' Disegna il romboide
   .MoveTo(points[0].X, points[0].Y)
   For i = 1 To 3
     .LineTo(points[i].X, points[i].Y)
   Next
   .LineTo(points[0].X, points[0].Y)
   .Stroke

' Disegna il punto al centro del romboide (centro della DrawingArea)
   .Arc(cx, cy, 5, Rad(0), Rad(360), False)
   .Fill
 End With

End