新建 WPF 项目: 在 Visual Studio 中创建一个新的 WPF 项目。
设计界面:
使用 XAML 设计速度表的界面。你可以使用 Canvas
控件来绘制表盘、刻度、指针等。确保设置好布局和样式。
<Window x:Class="YourNamespace.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Title="Speedometer" Height="400" Width="400">
<Grid>
<Canvas>
<!-- 绘制表盘、刻度等元素 -->
</Canvas>
</Grid>
</Window>
Canvas
中使用 Ellipse
绘制表盘,使用 Line
绘制刻度。同时,添加数字标签。<Ellipse Width="300" Height="300" Fill="LightGray" Canvas.Left="50" Canvas.Top="50"/>
<Line X1="200" Y1="100" X2="200" Y2="50" Stroke="Black" StrokeThickness="2"/>
<TextBlock Text="0" Canvas.Left="180" Canvas.Top="90"/>
<!-- 添加其他刻度和数字标签 -->
MainWindow.xaml.cs
文件中添加以下代码:using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace YourNamespace
{
public partial class MainWindow : Window
{
private double currentSpeed = 0;
private const double MaxSpeed = 300;
private readonly Line speedPointer;
public MainWindow()
{
InitializeComponent();
// 初始化指针
speedPointer = new Line
{
X1 = 200,
Y1 = 200,
Stroke = Brushes.Red,
StrokeThickness = 3
};
canvas.Children.Add(speedPointer);
// 使用定时器更新速度
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// 模拟速度变化
currentSpeed = currentSpeed < MaxSpeed ? currentSpeed + 5 : 0;
// 更新指针角度
UpdateSpeedometer();
}
private void UpdateSpeedometer()
{
// 计算指针角度
double angle = currentSpeed / MaxSpeed * 270 - 135;
// 使用 RotateTransform 旋转指针
var rotateTransform = new RotateTransform(angle);
speedPointer.RenderTransform = rotateTransform;
}
}
}
这个例子中,我们使用了一个定时器(DispatcherTimer
)来模拟速度的变化,并在定时器的 Tick
事件中更新指针的角度。UpdateSpeedometer
方法根据当前速度计算出指针的角度,并使用 RotateTransform
进行旋转。
确保在 MainWindow.xaml
文件中的 Canvas
中添加了名称为 canvas
的属性:
<Canvas x:Name="canvas">
<!-- 绘制其他元素 -->
</Canvas>
运行效果如:
这是一个基本的实例,你可以根据需要进一步优化和扩展,例如添加动画效果、改进界面设计等。
源代码获取:公众号回复消息【code:86861
】