2014-12-02 25 views
0

在WPF中,我有一個網格,其中包含一段內容,我需要使用兩根手指觸摸手勢來操縱它。下面的代碼適用於移動和縮放,但我需要知道如何限制最大和最小縮放值,例如100%到200%縮放。此外,我需要限制內容的移動,以便它保持在網格容器的大小內。限制操作接受兩個手指觸摸

代碼到目前爲止:

私人小組gridLeft_ManipulationStarting(發送者爲對象,例如作爲ManipulationStartingEventArgs)把手gridLeft.ManipulationStarting

e.ManipulationContainer = gridMapHolderLeft 
e.Mode = ManipulationModes.Scale + ManipulationModes.Translate 
e.Handled = True 
MyBase.OnManipulationStarting(e) 

結束子

私人小組gridLeft_ManipulationDelta(發送者爲對象,例如As ManipulationDeltaEventArgs)句柄gridLeft.ManipulationDelta

Dim element As UIElement = TryCast(e.Source, UIElement) 
Dim xform As MatrixTransform = TryCast(element.RenderTransform, MatrixTransform) 
Dim matrix As Matrix = xform.Matrix 
Dim delta As ManipulationDelta = e.DeltaManipulation 
Dim center As Point = e.ManipulationOrigin 
matrix.Translate(-center.X, -center.Y) 
matrix.Scale(delta.Scale.X, delta.Scale.Y) 
matrix.Translate(center.X, center.Y) 
matrix.Translate(delta.Translation.X, delta.Translation.Y) 
xform.Matrix = matrix 
e.Handled = True 
MyBase.OnManipulationDelta(e) 

End Sub

回答

0

您可以通過檢查生成的矩陣來限制比例。應用縮放後的決定值。如果該值高於最大值或低於最小比例值,則可以在應用矩陣之前簡單地從Sub返回。

在此示例中,最小值不是縮放比例(1.0),最大值是2x比例值(2.0)。

(請原諒我的VB代碼 - 我是一個C#開發人員的99.9%的時間!)

Private Sub gridLeft_ManipulationDelta(sender As Object, e As ManipulationDeltaEventArgs) Handles gridLeft.ManipulationDelta 

    Dim element As UIElement = TryCast(e.Source, UIElement) 
    Dim xform As MatrixTransform = TryCast(element.RenderTransform, MatrixTransform) 
    Dim matrix As Matrix = xform.Matrix 
    Dim delta As ManipulationDelta = e.DeltaManipulation 
    Dim center As Point = e.ManipulationOrigin 
    matrix.Translate(-center.X, -center.Y) 
    matrix.Scale(delta.Scale.X, delta.Scale.Y) 
    matrix.Translate(center.X, center.Y) 
    matrix.Translate(delta.Translation.X, delta.Translation.Y) 

    If matrix.Determinant >= 2.0 Or matrix.Determinant <= 1.0 Then 
    Return 
    End If 

    xform.Matrix = matrix 
    e.Handled = True 
    MyBase.OnManipulationDelta(e) 

End Sub 

我通過重構a WPF behaviour that provides just these features中旬方式。它是用C#編寫的,而不是VB編寫的,但是查看源代碼可能會讓你感興趣。特別是,the code in the 'ManipulationDeltaHandler' method

還有一些代碼檢查縮放元素的容器元素的邊界,以防止您將東西推出或縮放到視圖外。

我最終編寫了這個行爲,因爲Microsoft提供的TranslateZoomRotateBehavior只是不做我們需要的。

我希望那裏有東西有幫助。

+0

非常感謝Olitee,這真的很有幫助 – ShedSpotter 2014-12-02 14:19:29