优秀的编程知识分享平台

网站首页 > 技术文章 正文

C# 动态正反旋转-龙年(WinForm)时钟

nanyue 2024-11-12 11:46:52 技术文章 1 ℃

变量初始化:

 private double angle = 0;
 private int centerX = 350;
 private int centerY = 250;
 private int radius = 200;
 private string text = "123456789";
 private Font font = new Font("Arial", 82);
 private bool clockwise = true; // 用于控制旋转方向
 private int lineWidth = 29; // 用于控制圆的线宽
 private double pointer1Angle = 20; // 第一个指针的角度
 private double pointer2Angle = 100; // 第二个指针的角度
 private int pointerWidth = 29; // 指针的线宽

时间控件:

private void timer1_Tick(object sender, EventArgs e)
{
    if (clockwise)
    {
        this.angle += 5; // 顺时针旋转
        this.pointer1Angle += 5; // 顺时针旋转第一个指针
        this.pointer2Angle += 5; // 顺时针旋转第二个指针               
        this.pointer2Angle += 5;
    }
    else
    {
        this.angle -= 5; // 逆时针旋转
        this.pointer1Angle -= 5; // 逆时针旋转第一个指针
        this.pointer2Angle -= 5; // 逆时针旋转第二个指针
        this.pointer2Angle -= 5;
    }
    this.Refresh(); // 刷新窗体,触发重绘
}

图案展示:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Graphics dc = e.Graphics;

    // 画一个圆
    Pen circlePen = new Pen(Color.Blue, lineWidth); // 设置圆的线宽
    Rectangle circleBounds = new Rectangle(centerX - radius, centerY - radius, radius * 2, radius * 2);
    dc.DrawEllipse(circlePen, circleBounds);
  
    // 画两个指针
    Pen pointerPen = new Pen(Color.Red, pointerWidth); // 设置指针的线宽
    pointerPen.EndCap = LineCap.ArrowAnchor; // 添加箭头末端
    PointF pointer1End = new PointF(
        centerX + (float)(radius * Math.Cos(pointer1Angle * Math.PI / 180)),
        centerY + (float)(radius * Math.Sin(pointer1Angle * Math.PI / 180))
    );
    PointF pointer2End = new PointF(
        centerX + (float)(radius * Math.Cos(pointer2Angle * Math.PI / 180)),
        centerY + (float)(radius * Math.Sin(pointer2Angle * Math.PI / 180))
    );
    dc.DrawLine(pointerPen, new PointF(centerX, centerY), pointer1End);
    dc.DrawLine(pointerPen, new PointF(centerX, centerY), pointer2End);

    // 画一个实心圆
    SolidBrush solidBrush = new SolidBrush(Color.Red); // 设置实心圆的颜色
    Rectangle solidCircleBounds = new Rectangle(centerX - 50, centerY - 50, 100, 100); // 设置实心圆的位置和大小
    dc.FillEllipse(solidBrush, solidCircleBounds);

    // 画一个文字围绕圆的边框转圈
    double angleStep = 360.0 / text.Length;
    for (int i = 0; i < text.Length; i++)
    {
        double x = centerX + radius * Math.Cos((angle + i * angleStep) * Math.PI / 180);
        double y = centerY + radius * Math.Sin((angle + i * angleStep) * Math.PI / 180);
        PointF point = new PointF((float)x, (float)y);
        SizeF textSize = dc.MeasureString(text[i].ToString(), font);
        PointF textPosition = new PointF(point.X - textSize.Width / 2, point.Y - textSize.Height / 2);
        dc.DrawString(text[i].ToString(), font, Brushes.Fuchsia, textPosition);
    }
}

#冬日生活打卡季#

Tags:

最近发表
标签列表