Create An Analog Clock For Windows 10 Universal Application

In this article we are going to see how to create an analog clock in Windows 10 universal app using XAML and C#.

Create new Windows 10 universal application. For creating a new Windows 10 universal project, refer to the following:

I am going to use an ellipse and rectangle control to draw the clock.

Go to MainPage.Xaml page and write the following xaml code,

  1. <Grid Background="{StaticResourceApplicationPageBackgroundThemeBrush}">  
  2.     <Grid Width="300" Height="300">  
  3.         <Ellipse Width="300" Height="300" Fill="DarkOliveGreen"></Ellipse>  
  4.         <!--for Second -->  
  5.         <Rectangle Margin="150,0,149,150" Name="second" Stroke="White" Height="120" VerticalAlignment="Bottom">  
  6.             <Rectangle.RenderTransform>  
  7.                 <RotateTransform x:Name="secondHand" CenterX="0" CenterY="120" Angle="0" /> </Rectangle.RenderTransform>  
  8.         </Rectangle>  
  9.         <!-- for Minute -->  
  10.         <Rectangle Margin="150,49,149,151" Name="minute" Stroke="LightGreen">  
  11.             <Rectangle.RenderTransform>  
  12.                 <RotateTransform x:Name="minuteHand" CenterX="0" CenterY="100" Angle="0" /> </Rectangle.RenderTransform>  
  13.         </Rectangle>  
  14.         <!-- for Hour -->  
  15.         <Rectangle Margin="150,80,149,150" Name="hour " Stroke="LightYellow">  
  16.             <Rectangle.RenderTransform>  
  17.                 <RotateTransform x:Name="hourHand" CenterX="0" CenterY="70" Angle="0" /> </Rectangle.RenderTransform>  
  18.         </Rectangle>  
  19.     </Grid>  
  20. </Grid>  
We need 3 lines (rectangle) to show the hour, seconds, and minute hand on an analog clock. Set the angle zero (0) to transform the line from the center of the circle.

For seconds and minutes multiply the value by 6 to get the angle for the clock hand to transform. For hours multiply the hour by 30 to get the angle.

Using dispatcher time update the angle every second.

Now go to your code behind the page and write the following code.
  1. DispatcherTimer timer = newDispatcherTimer();  
  2. publicMainPage()  
  3. {  
  4.     this.InitializeComponent();  
  5.     timer.Interval = TimeSpan.FromSeconds(1);  
  6.     timer.Tick += Timer_Tick;  
  7.     timer.Start();  
  8. }  
  9. privatevoidTimer_Tick(object sender, object e)  
  10. {  
  11.     secondHand.Angle = DateTime.Now.Second * 6;  
  12.     minuteHand.Angle = DateTime.Now.Minute * 6;  
  13.     hourHand.Angle = (DateTime.Now.Hour * 30);  
  14. }  
Now run the app and see the expected output like the following screen.

APP

For more information on Windows 10 UWP, refer my e-book:
Read more articles on Universal Windows App:


Similar Articles