以前看到一些flash制作的很酷炫的時鐘,自己沒有藝術(shù)細胞,UI設(shè)計就免了,稍微介紹一下實現(xiàn),背景換成比較炫的圖片就可以成為比較炫的時鐘了
實現(xiàn)原理是根據(jù)時間計算角度,再計算時鐘指針的終點。
代碼比較簡單:
XAML: <Canvas>
<Ellipse Stroke="Transparent" Width="120" Height="120">
<Ellipse.Fill>
<RadialGradientBrush>
<GradientStop Color="White" Offset="0"></GradientStop>
<GradientStop Color="#DBDDE6" Offset="0.7"></GradientStop>
<GradientStop Color="#ACABC4" Offset="1"></GradientStop>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Line x:Name="lnHor" Stroke="Red" StrokeThickness="3" X1="60" Y1="60" X2="60" Y2="60"></Line>
<Line x:Name="lnMin" Stroke="Yellow" StrokeThickness="2" X1="60" Y1="60" X2="60" Y2="60"></Line>
<Line x:Name="lnSec" Stroke="Blue" StrokeThickness="2" X1="60" Y1="60" X2="60" Y2="60"></Line>
<Ellipse Stroke="White" Width="6" Height="6" Fill="Black" Canvas.Left="57" Canvas.Top="57">
</Ellipse>
</Canvas>
C#: DispatcherTimer timer;
const int secLen = 50;
const int minLen = 43;
const int horLen = 35;
DateTime dt;
int sec;
int min;
int hor;
double angle;
public Page()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Start();
timer.Tick += new EventHandler(timer_Tick);
}
void timer_Tick(object sender, EventArgs e)
{
dt = DateTime.Now;
sec = dt.Second;
min = dt.Minute;
hor = dt.Hour;
angle = Math.PI / 30 * sec - Math.PI / 2;
lnSec.X2 = 60 + Math.Cos(angle) * secLen;
lnSec.Y2 = 60 + Math.Sin(angle) * secLen;
angle = Math.PI / 1800 * (min * 60 + sec) - Math.PI / 2;
lnMin.X2 = 60 + Math.Cos(angle) * minLen;
lnMin.Y2 = 60 + Math.Sin(angle) * minLen;
angle = Math.PI / 21600 * (hor * 3600 + min * 60 + sec) - Math.PI / 2;
lnHor.X2 = 60 + Math.Cos(angle) * horLen;
lnHor.Y2 = 60 + Math.Sin(angle) * horLen;
}
代碼比較簡單,不多解釋。
運行效果: