[英]UWP Canvas drawing out of bounds
我有一个画布(不是 InkCanvas!),我可以在它上面画折线。 这工作得很好,但是像下面的 GIF 所示,绘制越界存在一个巨大的问题。
我的画布在 ScrollViewer 内,而 ScrollViewer 在 GridView 内。
我尝试使用以下事件处理程序捕获离开画布的指针:
canvas.PointerExited += Canvas_PointerExited;
canvas.PointerCaptureLost += Canvas_PointerCaptureLost;
但似乎这些事件的触发速度太慢了。
我尝试使用画布的 Clip 属性,但行为没有变化。 UWP 画布没有“ClipToBound”属性。
我的整个视图是在 Code-Behind 中生成的,因为我必须在一个视图上生成多个画布。
有没有办法阻止这种行为?
编辑1:
根据要求:更深入地了解我的代码。
XAML 页面如下所示:
<Grid x:Name="BoundingGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="15*"/>
</Grid.RowDefinitions>
<Grid x:Name="InkGrid" VerticalAlignment="Top" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" />
<Grid x:Name="CanvasGrid" Grid.Row="1" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" VerticalAlignment="Top"/>
</Grid>
这一切都在一个页面中。
我背后的代码如下所示:
我的构造函数:
public ImprovedCanvasManager(Grid boundingGrid, Grid overviewGrid, string filepath, double height)
{
drawCanvas = new Canvas();
overviewGrid.Loaded += OverviewGrid_Loaded;
overviewGrid.SizeChanged += OverviewGrid_SizeChanged;
RowDefinition rd = new RowDefinition();
rd.Height = new GridLength(height);
overviewGrid.RowDefinitions.Add(rd);
InitializeScrollViewer();
Grid.SetRow(scroll, overviewGrid.RowDefinitions.Count);
Grid.SetColumn(scroll, 0);
scroll.Content = drawCanvas;
overviewGrid.Children.Add(scroll);
LoadImage(filepath);
}
public ImprovedCanvasManager(Grid boundingGrid, Grid overviewGrid, Grid inkToolGrid, string filepath, double height = 1000) : this(boundingGrid, overviewGrid, filepath, height)
{
AddDrawingToolsToCanvas(inkToolGrid, overviewGrid);
EnableDrawingOnCanvas(drawCanvas);
}
我只有两个构造函数,使我可以轻松地实例化具有绘图能力和不具有绘图能力的画布。
这就是我初始化 ScrollViewer 的方式:
private void InitializeScrollViewer()
{
scroll = new ScrollViewer();
scroll.VerticalAlignment = VerticalAlignment.Top;
scroll.VerticalScrollMode = ScrollMode.Auto;
scroll.HorizontalScrollMode = ScrollMode.Auto;
scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
scroll.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
scroll.ZoomMode = ZoomMode.Enabled;
scroll.ManipulationMode = ManipulationModes.All;
scroll.MinZoomFactor = 1;
scroll.MaxZoomFactor = 3;
}
这些是影响任何视图构建的唯一代码行。
编辑2:
我的画布没有填充左侧的周围网格,而是填充了底部。
PointerMoved
处理程序中的代码应该是相对于画布的。
private void OnPointerMoved(object sender, PointerRoutedEventArgs e)
{
var point = e.GetCurrentPoint(canvas); // <-- relative to canvas.
var x = point.Position.X;
var y = point.Position.Y;
x = Math.Max(x, 0);
y = Math.Max(y, 0);
x = Math.Min(canvas.ActualWidth, x);
y = Math.Min(canvas.ActualHeight, y);
// add point to polyline...
}
如果 x/y 为负数或大于画布的大小,则它们越界。 您可以像上面的代码那样将点限制在画布的边界上,也可以完全丢弃该点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.