为WPF InkCanvas编程创建笔画的性能问题



我在InkCanvas()上取消触摸事件时问了一个问题。Net Framework),没有得到答案,所以我试图将InkCanvas设置为HitTestVisiblefalse,并通过驱动程序的API获得StylusPoints。这些点现在手动放入Strokes中,然后放入绑定的StrokeCollection中。这样,我只能通过触控笔而不是触摸或鼠标获得积分(我知道UWPInkCanvas默认可以这样做,但遗憾的是WPF太老了,没有得到微软的正确支持)。

但是我对这个方法的速度有一个问题。我将每个点(以及之前的点)制作成Stroke,并将它们放入StrokeCollection中。这就导致了"缓慢"的增长。Stroke。如果我写一些东西,它只会在3/4左右显示出来,当我已经用笔写完的时候,然后在半秒后完全显示出来。你有什么想法,如何使这个更快,使它看起来像一个正常使用的InkCanvas?或者可以回答前面的问题;)

这是我的代码:

private void TabLib_DataReceived(object sender, EventArgs e)
{
float pressureFactor = e.pressure / 1024f;
StylusPoint newPoint = new StylusPoint()
{
PressureFactor = pressureFactor,
X = e.xPos,
Y = e.yPos
};
if (pressureFactor == 0) // that means the pen has left or entered the tablet
{
_oldPressurePoint = newPoint;
return;
}
StylusPointCollection pointList = new StylusPointCollection();
pointList.Add(_oldPressurePoint);
pointList.Add(newPoint);
Stroke stroke = new Stroke(pointList, _penDrawingAttributes);
// used a dispatcher begininvoke because of DrawnStrokes are bound to the UI thread.
_tabletWindow.Dispatcher.BeginInvoke(new Action<Stroke>((newStroke) =>
{
DrawnStrokes.Add(newStroke); // DrawnStrokes is the bound StrokeCollection
}), stroke);
_oldPressurePoint = newPoint;
}

我也想过创建一个笔画,只添加点,但这似乎不起作用。如果你已经添加了一个笔画,你不能给这个笔画添加点,对吗?

您应该只在必要时创建一个新的Stroke,并将点添加到当前Stroke的StylusPoints集合中。

这是一个流畅的工作示例,从鼠标输入在InkCanvas上的画布上创建笔画数据。

<Grid>
<InkCanvas x:Name="inkCanvas" IsHitTestVisible="False"/>
<Canvas Background="Transparent"
MouseLeftButtonDown="CanvasMouseLeftButtonDown"
MouseLeftButtonUp="CanvasMouseLeftButtonUp"
MouseMove="CanvasMouseMove"/>
</Grid>

后面有以下代码:

private Stroke stroke;
private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var pos = e.GetPosition(inkCanvas);
var points = new StylusPointCollection
{
new StylusPoint(pos.X, pos.Y)
};
stroke = new Stroke(points, inkCanvas.DefaultDrawingAttributes);
inkCanvas.Strokes.Add(stroke);
}
private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
stroke = null;
}
private void CanvasMouseMove(object sender, MouseEventArgs e)
{
if (stroke != null)
{
var pos = e.GetPosition(inkCanvas);
stroke.StylusPoints.Add(new StylusPoint(pos.X, pos.Y));
}
}

最新更新