在绘图过程中有对某个或某些图元进行比例缩小或放大的要求,通过比例变换可以实现它。比例缩放前需要将要变换的图元放到选择集中,变换只针对选择集中的图元进行。具体操作时,通过单击菜单选项或命令按钮就可以实现比例缩放,所以不必像前面几种变换那样建立专门的交互操作类,但仍然需要在CGElement类中添加相应的方法并在派生类中实现它。
在CGElement类中添加Scale 方法
在CGElement 类中添加一个Scale方法。该方法有3个参数:g为Graphics对象,指定绘图表面,scalex和scaley分别为横向和纵向上的缩放比例。
code.vb.net
'比例缩放图元
Public MustOverride Sub Scale(ByVal g As Graphics,
ByVal scalex As Single, ByVai scaley As Single)
在派生类中重写Scale方法
在CGElement类中添加Scale方法以后,在各派生类中重写该方法,确定变换以后图元控制点的坐标。
1. 在CLine类中重写Scale方法
下面在CLine类中重写Scale方法,计算比例变换以后直线段起点和终点的坐标。
code.vb.net
'比例变换
Public Overrides Sub Scale(ByVal g As Graphics, ByVal sx As Single, ByVal sy As Single)
With m_Begin
.X = .X * sx
.Y = .Y * sy
End With
With m_End
.X = .X * sx
.Y = .Y * sy
End With
End Sub
2. 在CRectangle类中重写Scale方法
下面在CRe ctaggle类中重写基人的Scale方法,计算镜像变换以后矩彤起点和终点的坐标值。
code.vb.net
'比例变换
Public Overrides Sub Scale(ByVal g As Graphics, ByVal sx As Single, ByVal sy As Single)
With m_basePos
.X = .X * sx
.Y = .Y * sy
End With
With m_desPos
.X = .X * sx
.Y = .Y * sy
End With
End Sub
3. 在CCircle类中重写Scale方法
下面在CCircle类中重写Scale方法,计算变换以后圆的圆心和圆上一点的坐标值。
code.vb.net
'比例变换
Public Overrides Sub Scale(ByVal g As Graphics, ByVal sx As Single, ByVal sy As Single)
With m_Center
.X = .X * sx
.Y = .Y * sy
End With
With m_PCircle
.X = .X * sx
.Y = .Y * sy
End With
End Sub
4. 在CArc类中重写Scale方法
在CArc类中重写基类的Scale方法,计算变换以后圆弧的圆心、起点和终点的坐标值。
code.vb.net
'比例变换
Public Overrides Sub Scale(ByVal g As Graphics, ByVal sx As Single, ByVal sy As Single)
With m_Center
.X = .X * sx
.Y = .Y * sy
End With
With m_Begin
.X = .X * sx
.Y = .Y * sy
End With
With m_End
.X = .X * sx
.Y = .Y * sy
End With
End Sub
实现比例变换
在前面程序的基础上添加下面的代码,确定在单击"比例放大"菜单项时将图形放大到1.2倍,单击"比例缩小"菜单项时将图形缩小到原图的0.8倍。
code.vb.net
Private Sub mnuTZoomin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuTZoomout.Click
Dim g As Graphics = Me.CreateGraphics()
ScaleZoom(g, 1.2, 1.2)
End Sub
Private Sub mnuTZoomout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuTZoomin.Click
Dim g As Graphics = Me.CreateGraphics()
ScaleZoom(g, 0.8, 0.8)
End Sub
Public Sub ScaleZoom(ByVal g As Graphics, ByVal dx As Single, ByVal dy As Single)
Dim i As Integer
For i = 0 To geSels.Count - 1
geSels(i).draw(g, geDrawMode.Delete)
geSels(i).scale(g, dx, dy)
geSels(i).draw(g, geDrawMode.Selec)
Next
End Sub
运行程序以后,绘图,选择图元,然后进行比例缩放。对图6-2中的图形进行放大和缩小以后的图形效果如图6-6和图6-7所示。
\[\]
图6-6放大选定图元
\[\]
图6-7缩小选定图元