2015-05-04 214 views
0

我将用60线形状(使用Visual Studios PowerPack)来创建表单。我希望用户能够使用键盘上的左和右按钮旋转90度的形状。如何旋转线形90度?

这样做的最好方法是什么?我尝试了其他方法,但是这相当于1000行代码,我仍然在学习,我想知道最佳实践。

非常感谢!

+0

取决于您的线条如何存储(坐标或图像)。如果你只想翻转90度,你可以切换x和y。 (顺时针还是逆时针?) –

+0

这将有助于查看一些示例代码,演示如何在窗体上使用至少一行。 –

回答

1

我假设你已经写过零件来处理几何图形,并询问如何重新使用代码,而不用重复60行。这很重要,因为从围绕中点或围绕起点旋转的问题来看,并非100%清楚,因为LineShape类型确实区分了开始点和结束点。没有这些信息,我无法为您编写几何代码。

第一部分并没有那么糟糕。我们只是设置了几个方法,可以处理旋转任何行:

'Note that rotating a line 90 degrees around it's midpoint 
' will give the same result whether you go clockwise or counterclockwise, 
' but I figure you'll want to adapt this for other shapes later, or that 
' you're rotating around the line's starting point 

Private Sub RotateClockwise(ByVal line As LineShape) 
    'Code to rotate the passed line clockwise here 
    Dim x1 As Integer = line.X1 
    Dim y1 As Integer = line.Y1 
    Dim x2 As Integer = line.X2 
    Dim y2 As Integer = line.Y2 


End Sub 

Private Sub RotateCounterclockwise(ByVal line As LineShape) 

    'Code to rotate the passed line counter-clockwise here 

End Sub 

Private Sub LineShape_KeyDown(Byval sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) 
    'Which line? 
    Dim line As LineShape = TryCast(sender, LineShape) 
    If line Is Nothing Then Exit Sub 

    'Left key? 
    If e.KeyCode = Keys.Left Then RotateCounterclockwise(line) 

    'Right key? 
    If e.KeyCode = Keys.Right Then RotateClockwise(line) 
End Sub 

这是它变得棘手。请注意,上述事件处理程序缺少Handles关键字。我们希望将事件处理程序所有的LineShape控件连接到这一个方法。这将是一个有点重复,因为这意味着你的形式在每一行代码的另一行,但它是不是需要编写上面的代码你行的所有更好:

Dim Lines As New List(Of LineShape)() 
Lines.Add(LineShape1) 
Lines.Add(LineShape2) 
'... 
Lines.Add(LineShape60) 
For Each Line As LineShape In Lines 
    AddHandler Line.KeyDown, AddressOf LineShape_KeyDown 
Next 

该代码去在你的表格的构造函数之后InitializeComponent()方法。

我可以做的更好,如果线形类型是一个真正的控制(For EAch Line In Me.Controls.OfType(Of LineShape)()),但该文档显示这其实是一个Component,而不是Control

+0

你好,我没有添加线几何的任何代码,抱歉的混乱。如果可能的话,我希望能够将线90度旋转到中点。感谢您的帮助,我真的很感激! :) – snipar

+1

这里值得注意的是,删除表单的处理代码中的处理程序非常重要。未删除的处理程序将固定这些对象并阻止GC。 –

0

或者,你也可以继承LineShape建设“可旋转”到您的新类为:

Imports Microsoft.VisualBasic.PowerPacks 
Public Class MySmartLine 
    Inherits LineShape 
    Private Sub RotateClockwise() 
     'Code to rotate clockwise here 
     Me.X1 = ... 
     Me.X2 = ... 
    End Sub 
    Private Sub RotateAntiClockwise() 
     'Code to rotate anti clockwise here 
    End Sub 
    Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs) 
     MyBase.OnKeyDown(e) 
     If e.KeyCode = Keys.Left Then 
      RotateAntiClockwise() 
     End If 
     If e.KeyCode = Keys.Right Then 
      RotateClockwise() 
     End If 
    End Sub 
End Class 

建设项目后,自定义MySmartLine组件将出现在你的工具箱,你可以代替使用LineShape