<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:drawable="clr-namespace:Clock2"
x:Class="Clock2.MainPage">
<ContentPage.Resources>
<drawable:GraphicsDrawable x:Key="drawable"/>
</ContentPage.Resources>
<GraphicsView x:Name="gView" Drawable="{StaticResource drawable}"/>
</ContentPage>
using Microsoft.Maui.Graphics;
using System.Timers;
namespace Clock2;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
gView.Invalidate();
}
}
public class GraphicsDrawable : IDrawable
{
public void Draw(ICanvas canvas, RectF dirtyRect)
{
canvas.ResetState();//重置状态
canvas.StrokeLineCap = LineCap.Round;//绘制表盘(圆形)
canvas.FillColor = Colors.Gray;//设置表盘颜色灰色
canvas.Translate(dirtyRect.Center.X, dirtyRect.Center.Y);//将表盘坐标原点放到画板中央
float scale = Math.Min(dirtyRect.Width / 220, dirtyRect.Height / 220);//获取画板边长的最小值
canvas.Scale(scale, scale);//按窗体比例变化而变化
canvas.FillCircle(0, 0,4);//填充圆形(x,y,半径2个像素)
//canvas.DrawString("1", 0, 0, HorizontalAlignment.Left);
int ii = 12;
for (int angle = 0; angle < 360; angle += 6)
{
if (angle%30 == 0)
{
canvas.StrokeColor = Colors.Gray;//设置线条颜色
canvas.DrawString(ii.ToString(), 0, -95, HorizontalAlignment.Center);//填充文字(x,y,半径2个像素)
ii++;
if (ii >= 12)
{
ii = ii - 12;
}
}
canvas.FillCircle(0, -90, angle % 30 == 0 ? 4 : 2);//填充圆形(x,y,半径2个像素)
canvas.Rotate(6);//旋转6度
}
DateTime now = DateTime.Now;//获取当前时间
canvas.StrokeColor = Colors.Gray;//设置线条颜色
canvas.DrawString(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), 0, 40, HorizontalAlignment.Center);
//小时
canvas.StrokeColor = Colors.Gray;//设置线条颜色
canvas.StrokeSize = 20;//线条的宽度
canvas.SaveState();//保存画布状态
canvas.Rotate(now.Hour * 30 + now.Minute / 2f);//旋转角度
canvas.DrawLine(0, 0, 0, -50);//绘制指针
//分针
canvas.StrokeColor = Colors.Blue;//设置线条颜色
canvas.StrokeSize = 10;//线条的宽度
canvas.SaveState();//保存画布状态
canvas.Rotate(6*now.Minute);//旋转角度
canvas.DrawLine(0, 0, 0, -70);//绘制指针
//秒
canvas.StrokeColor = Colors.Red;//设置线条颜色
canvas.StrokeSize = 2;//线条的宽度
canvas.SaveState();//保存画布状态
canvas.Rotate(6 * now.Second-180);//旋转角度
canvas.DrawLine(0, 0, 0, -80);//绘制指针
}
}