时钟






4.92/5 (8投票s)
使用线性变换的简单时钟
引言
这个简单的技巧适用于 WPF 初学者。 这将帮助你理解 RotateTransform
的用法,通过它可以创建一个简单的时钟。 仅仅改变 Angle
在 RotateTransform
中,对于每条线(时针、分针和秒针),就可以制作一个简单的时钟。
背景
这需要对 XAML 的使用有一个简单的理解。 并且,对 C# 的基本知识就足够了,因为我们不会添加任何复杂的项目。
Using the Code
XAML 部分
让我们首先看一下 XAML 部分。 首先,将在 Canvas
内部添加 Canvas
,然后相应地添加 Ellipse
、Lines
、TextBlock
。 现在让我们看看如何通过 3 个简单的步骤制作时钟。
步骤 1:添加类似时钟的外观
首先,创建一个 Canvas
,设置 Height = "200"
和 Width ="200"
,并在 Canvas
内部绘制一个椭圆,然后用径向渐变画笔填充椭圆。 注意:Grid
背景设置为“Black
”。 然后添加用于每 5 分钟的线条,并按照如下方式对这些线条进行变换(对于“十二点”,我们不使用 RenderTransform
,因为它笔直向下)。
<Line Name="twelve"
X1="100" Y1="10"
X2="100" Y2="2"
Stroke="White"
StrokeThickness="2"/>
<Line Name="One"
X1="100" Y1="5"
X2="100" Y2="2"
Stroke="White"
StrokeThickness="2">
<Line.RenderTransform>
<RotateTransform Angle="30" CenterX="100" CenterY="100"/>
</Line.RenderTransform>
</Line>
<Line Name="Two"
X1="100" Y1="5"
X2="100" Y2="2"
Stroke="White"
StrokeThickness="2">
<Line.RenderTransform>
<RotateTransform Angle="60" CenterX="100" CenterY="100"/>
</Line.RenderTransform>
</Line>
<!--
Similarly add for the remaining Lines by changing "Angle"
-->
在添加十二条带有变换的线条后,现在我们将添加四个文本块来显示时钟上的数字 3、6、9 和 12。
步骤 2:添加时钟指针
现在是时候添加时针、分针、秒针和中心椭圆了。 到现在为止,设计器窗口将显示一个时钟外观。 对于所有的时针和分针
<Line Name="mins"
StrokeThickness="5"
Stroke="Navy" StrokeEndLineCap="Triangle"
StrokeStartLineCap="Round"
X2="100" Y2="30"
X1="100" Y1="100"/>
<Line Name="hrs"
StrokeThickness="6"
Stroke="Navy"
StrokeStartLineCap="Round"
StrokeEndLineCap="Triangle"
X2="100" Y2="45"
X1="100" Y1="100"/>
<Line Name="secs"
StrokeThickness="3"
Stroke="Blue" StrokeEndLineCap="Round"
StrokeStartLineCap="Round"
X2="100" Y2="15"
X1="100" Y1="115"/>
<Ellipse Height="10" Width="10"
Fill="Blue"
StrokeThickness="1" Margin="95,95,0,0"
Stroke="White"/>
C# 部分
步骤 3:添加定时器事件代码
现在是时候使用 System.DateTime
来使秒针、分针和时针进行变换了。 添加并启动定时器。 然后,对于每一秒,它将执行以下方法。 RotateTransform
帮助以给定的轴旋转线条。
RotateTransform rt1 = new RotateTransform(_seconds, 100, 100);
_seconds
仅仅是角度,然后是 CenterX
和 CenterY
。 由于我们有一个高度为 200 且宽度为 200 的画布,因此中心点是 100,100。 因此,现在变换是相对于中心完成的。
同样适用于分针和时针。
void timers_Tick(object sender, EventArgs e)
{
// get seconds, and move the second hand
int nowSecond = DateTime.Now.Second * 6; // times 6 to get rotate angle
secs.RenderTransform = new RotateTransform(nowSecond, 100, 100);
int nowMinute = DateTime.Now.Minute * 6; // times 6 to get rotate angle
mins.RenderTransform = new RotateTransform(nowMinute, 100, 100);
int nowHour = DateTime.Now.Hour;
if (nowHour > 12)
{
nowHour -= 12; // only 12 hours on the clock face
}
nowHour *= 30; // angle for the hourhand
nowHour += nowMinute / 12; // plus offset for minutes (60 minutes / 5)
hrs.RenderTransform = new RotateTransform(nowHour, 100, 100);
}
关注点
这有助于了解如何在 XAML 和 C# 中使用 RotateTransform
来旋转线条。 在我的下一篇文章中,我将尝试添加更多内容,以便我们可以制作一些类似 Windows 7 桌面时钟小工具并带有主题的内容。
历史
- 源文件已正确添加
- 删除了重复的 XAML 代码
- 小时计算错误,现在已更正(2013 年 3 月 26 日)
- 删除了默认窗口,添加了右键单击选项以设置颜色并启用了拖动