為建立中文知識庫加塊磚 ——中科大胡不歸
0. 前言
項目上需要繪制坐標軌跡找田,找開源組件也是費盡周折,最后發(fā)現(xiàn)Canvas + Polyline就可以基本的軌跡功能孩革。為使軌跡不過于單調增加了網(wǎng)格線背景广鳍。
學習WPF: 第6個月箕母。
1. 實現(xiàn)原理
網(wǎng)格線的繪制主要依賴窗口的寬高和設定的間隔計算,畫多少行砾隅,畫多少列误阻,畫多長,畫多高晴埂。
支持窗口縮放只要是監(jiān)聽 SizeChanged 的回調事件究反,窗口尺寸變化,實現(xiàn)重繪和更新儒洛。
2. View代碼
<Grid>
<Canvas x:Name="MyGrid">
</Canvas>
<WrapPanel VerticalAlignment="Bottom" HorizontalAlignment="Center">
<Button Click="ButtonPath_OnClick">左手軌跡</Button>
<Button Click="ButtonDrawCircle_OnClick">右手畫圓</Button>
</WrapPanel>
</Grid>
3. 后端代碼
namespace DrawGrid
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
InitData();
SizeChanged += MainWindow_Resize;
}
private void MainWindow_Resize(object sender, EventArgs e)
{
MyGrid.Children.Clear();
GridTool.Draw(MyGrid);
DrawPath(MyGrid);
}
private readonly Polyline _line = new Polyline();
private readonly PointCollection _collection = new PointCollection();
private readonly Random _random = new Random();
private void ButtonPath_OnClick(object sender, RoutedEventArgs e)
{
_collection.Add(new Point(_random.Next(1, (int)ActualWidth),_random.Next(1, (int)ActualHeight)));
MyGrid.Children.Clear();
GridTool.Draw(MyGrid);
DrawPath(MyGrid);
}
private void DrawPath(Panel panel)
{
_line.Points = _collection;
_line.Stroke = new SolidColorBrush(Colors.Black);
_line.StrokeThickness = 1;
panel.Children.Add(_line);
}
private void ButtonDrawCircle_OnClick(object sender, RoutedEventArgs e)
{
MyGrid.Children.Clear();
GridTool.DrawCircle(MyGrid);
}
private void InitData()
{
_collection.Add(new Point(20,20));
_collection.Add(new Point(40,25));
_collection.Add(new Point(60,40));
_collection.Add(new Point(80,120));
_collection.Add(new Point(120,140));
_collection.Add(new Point(200,180));
}
}
}
4. DrawGrid代碼
public static void Draw(Canvas canvas)
{
var gridBrush = new SolidColorBrush {Color = Colors.Red};
double scaleX = 30;
double currentPosY = 0;
currentPosY += scaleX;
while (currentPosY < canvas.ActualHeight)
{
Line line = new Line
{
X1 = 0,
Y1 = currentPosY,
X2 = canvas.ActualWidth,
Y2 = currentPosY,
Stroke = gridBrush,
StrokeThickness = 0.1
};
canvas.Children.Add(line);
currentPosY += scaleX;
}
double scaleY = 30;
double currentPosX = 0;
currentPosX += scaleY;
while (currentPosX < canvas.ActualWidth)
{
Line line = new Line
{
X1 = currentPosX,
Y1 = 0,
X2 = currentPosX,
Y2 = canvas.ActualHeight,
Stroke = gridBrush,
StrokeThickness = 0.1
};
canvas.Children.Add(line);
currentPosX += scaleY;
}
}
封裝成工具類精耐,源碼 。