UWP现在的开发确实很方便,不过资料真的好少啊。。。
前些天看到同学有实实现自定义的时钟,这东东挺简单的,就自己也写个,没成想,遇到个坑,费了好长时间,记下来一下。
效果图:
画个圆,三条线就好。XAML代码如下:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Ellipse x:Name="ellipse" Stroke="Black"/> <Line x:Name="line_Second" Stroke="Red" StrokeThickness="3"/> <Line x:Name="line_Minute" Stroke="Blue" StrokeThickness="2"/> <Line x:Name="line_Hour" Stroke="Black" StrokeThickness="1"/> </Grid>
C#代码:
public sealed partial class MainPage : Page { DispatcherTimer timer;//定义定时器 double ScreenHeight; double ScreenWidth; double ellipseWidth; const double PI = 3.1415926; const double lineLength_Second=250; const double lineLenght_Minute = 200; const double lineLenght_Hour = 150; static int second; static int minute; static int hour; public MainPage() { this.InitializeComponent(); timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 1); timer.Tick += Timer_Tick;//每秒触发这个事件,以刷新指针 timer.Start(); } private void Timer_Tick(object sender, object e) { line_Second.X1 = Window.Current.Bounds.Width / 2; line_Second.Y1 = Window.Current.Bounds.Height / 2; line_Minute.X1= Window.Current.Bounds.Width / 2; line_Minute.Y1=Window.Current.Bounds.Height / 2; line_Hour.X1= Window.Current.Bounds.Width / 2; line_Hour.Y1= Window.Current.Bounds.Height / 2; //秒针 second = DateTime.Now.Second; double radius_second = PI * second / 30; line_Second.X2 = lineLength_Second * Math.Sin(radius_second)+ line_Second.X1; line_Second.Y2 = line_Second.Y1- lineLength_Second * Math.Cos(radius_second); //分针 minute = DateTime.Now.Minute; double radius_minute= PI * minute / 30; line_Minute.X2 = lineLenght_Minute * Math.Sin(radius_minute) + line_Minute.X1; line_Minute.Y2 = line_Minute.Y1-lineLenght_Minute * Math.Cos(radius_minute); //时针 hour = DateTime.Now.Hour; double radius_hour = hour*PI/6+radius_minute/12; line_Hour.X2 = lineLenght_Hour * Math.Sin(radius_hour) + line_Hour.X1; line_Hour.Y2 = line_Hour.Y1 - lineLenght_Hour * Math.Cos(radius_hour); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); //获取窗口实际长宽,以下就是为了适用不同窗体, //圆甚至直线的长度也要随窗体变化 ScreenHeight = Window.Current.Bounds.Height; ScreenWidth = Window.Current.Bounds.Width; ellipseWidth = ScreenWidth > ScreenHeight ? ScreenHeight - 20 : ScreenWidth - 20; ellipse.Height = ellipseWidth; ellipse.Width = ellipseWidth; } }
基础不太好,结果好久才把指针搞对,原因是我对UWP的角度的0°位置不清楚:
窗体左上角为坐标原点,而角度的0°位置如图,调了好久,我还以为写错了,原来是坐标系搞错了,哎
时间: 2024-11-05 15:48:18