使用鼠标和触摸在ScrollViewer中的画布中绘制矩形

本文关键字:布中 绘制 ScrollViewer 鼠标 触摸 | 更新日期: 2023-09-27 18:21:48

我在ScrollViewer中得到了一个画布。

<ScrollViewer x:Name="svWorkSpace" Visibility="Collapsed" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
                      Tapped="svWorkSpace_Tapped"
                      PointerPressed="svWorkSpace_PointerPressed"
                      PointerMoved="svWorkSpace_PointerMoved"
                      PointerReleased="svWorkSpace_PointerReleased">
            <Grid>
                <Image x:Name="cvWorkImage"/>
                <Canvas x:Name="cvWorkSpace"/>
            </Grid>
        </ScrollViewer>

PointerPressed代码中,我捕捉起点,在PointerMoved程序中,我在指针移动时绘制一个矩形(同时删除我移动的尾部矩形,在画布中只保留一个矩形。我使用此方法实现了矩形大小调整效果)PointerReleased将接受最后一个矩形。

使用鼠标触摸设备一切正常,但不使用手指。当我移动手指时,图像会滚动。

尝试将代码移动到Canvas中,如下所示。无法同时使用鼠标和触摸绘制矩形。

<ScrollViewer x:Name="svWorkSpace" Visibility="Collapsed" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
            <Grid>
                <Image x:Name="cvWorkImage"/>
                <Canvas x:Name="cvWorkSpace"
                      Tapped="svWorkSpace_Tapped"
                      PointerPressed="svWorkSpace_PointerPressed"
                      PointerMoved="svWorkSpace_PointerMoved"
                      PointerReleased="svWorkSpace_PointerReleased"/>
            </Grid>
        </ScrollViewer>

请给我指正确的方向。

使用鼠标和触摸在ScrollViewer中的画布中绘制矩形

当ScrollViewer接收到基于触摸的PointerPressed时,它将转到"直接操纵"以响应平移和缩放。Direct Manipulation捕获指针输入,因此Canvas的PointerMoved和PointerReleased事件不会触发。无事件->无绘图。

ScrollViewer使用鼠标平移或缩放,以便鼠标事件能够进入画布。

假设您总是希望Canvas处理指针事件而不是滚动(也许网格中还有其他控件使用ScrollViewer),您可以将Canvas的ManipulationMone设置为all,让Canvas块上的触摸触摸ScrollViewer

<Canvas x:Name="cvWorkSpace"
    Background={ThemeResource WorkSpaceBackgroundBrush}
    Tapped="svWorkSpace_Tapped"
    ManipulationMode="All"
    PointerPressed="svWorkSpace_PointerPressed"
    PointerMoved="svWorkSpace_PointerMoved"
    PointerReleased="svWorkSpace_PointerReleased"/>

如果您有时只想让画布处理指针事件,那么您可以将ManipulationMode切换回System,让ScrollViewer处理它。如果您想用单点触摸在画布上绘制,并用多点触摸进行平移/缩放,那么您就可以在画布上处理Manipulation事件以进行平移和缩放。

还要确保Canvas不是透明的,并允许指针事件传递到它后面的任何东西。如果你想在图像上绘制,你可以设置一个ImageBrush,将图像作为Canvas的背景,而不是使用单独的image控件。