在 Avalonia 中实现一个简单的画板功能,核心是利用
Canvas作为绘图容器,配合鼠标事件(按下、移动、释放)实时绘制线条。它不依赖 Skia 或 OpenGL 渲染层,纯用 Avalonia 的矢量绘图能力即可完成基础手写/绘图效果。
1. XAML 中定义 Canvas 和事件绑定
在窗口或用户控件的 XAML 中添加
Canvas,并绑定鼠标交互事件:
<Canvas Name="DrawingCanvas"
PointerPressed="OnPointerPressed"
PointerMoved="OnPointerMoved"
PointerReleased="OnPointerReleased"
Background="White" />
注意:
Pointer*是 Avalonia 推荐的跨平台输入事件(替代旧版 Mouse*),支持触控和鼠标;确保
Background设为非空(如
White或
Transparent),否则可能无法捕获事件。
2. 在后台代码中记录路径并动态绘制
使用
Shape(如
Polyline)实时添加到 Canvas,比直接操作 DrawingContext 更易维护: 声明一个
Polyline _currentLine字段,用于暂存当前笔画 按下(
PointerPressed)时创建新
Polyline,设置 Stroke、StrokeThickness,并添加到 Canvas 子元素 移动(
PointerMoved)时将当前坐标追加到
Polyline.Points释放(
PointerReleased)时清空引用,结束当前笔画
示例关键逻辑(C#):
private Polyline _currentLine;
private void OnPointerPressed(object sender, PointerPressedEventArgs e) {
var point = e.GetPosition(DrawingCanvas);
_currentLine = new Polyline {
Stroke = Brushes.Black,
StrokeThickness = 2,
Points = new PointCollection { point }
};
DrawingCanvas.Children.Add(_currentLine);
}
private void OnPointerMoved(object sender, PointerEventArgs e) {
if (_currentLine == null) return;
var point = e.GetPosition(DrawingCanvas);
_currentLine.Points.Add(point);
}
private void OnPointerReleased(object sender, PointerReleasedEventArgs e) {
_currentLine = null;
}
3. 可选:支持颜色、粗细、橡皮擦等基础功能
通过绑定 UI 控件(如
ColorPicker、
Slider)动态修改
_currentLine.Stroke和
StrokeThickness。橡皮擦可切换为“透明画笔”或改用
Rectangle覆盖(需开启
IsHitTestVisible=false避免干扰)。
清空画布只需:
DrawingCanvas.Children.Clear();
4. 注意性能与体验细节
高频移动下点太多会卡顿,可做简单“距离阈值”优化:仅当新点与上一点距离 > 2px 才添加 启用Canvas.IsItemsHost="True"不必要,
Children已足够;避免每帧重绘,Avalonia 会自动批处理 若需导出为 PNG,可用
RenderTargetBitmap渲染整个 Canvas
基本上就这些。不需要引入额外包,Avalonia 11+ 内置能力已完全够用。画板逻辑清晰,扩展撤销/重做、贝塞尔平滑、图层等功能也都有成熟路径。
