十年前在东北学绘图无聊做完雪花屏保之后,又做了个时钟控件,然后用这个控件做了个时钟屏保。学会了绘图之后就可以自己做用户控件了。C#winform的用户控件只要继承UserControl类即可。
先拖一个用户控件UserControl,然后自己实现绘图和属性就可以自定义控件。
就是在定时器逻辑里按属性绘制时钟表盘
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
namespace UserClock
{
public class UserClock:UserControl
{
private DateTime time;
private Timer timer1;
private System.ComponentModel.IContainer components;
public UserClock()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// UserClock
//
this.Name = "UserClock";
this.ResumeLayout(false);
}
private void timer1_Tick(object sender, EventArgs e)
{
this.time = DateTime.Now;
this.Refresh();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics pDC = e.Graphics;
Pen pen = new Pen(this.ForeColor);
SolidBrush brush = new SolidBrush(this.ForeColor);
InitCoordinates(pDC);
DrawDots(pDC, brush);
DrawHourHand(pDC, pen);
DrawMineteHand(pDC, pen);
DrawSecondHand(pDC, pen);
}
protected void InitCoordinates(Graphics pDC)
{
if (this.Width == 0 || this.Height == 0)
{
return;
}
pDC.TranslateTransform(this.Width/2,this.Height/2);//平移坐标原点
pDC.ScaleTransform(this.Height / 250F, this.Width / 250F);//调整比例大小
}
protected void DrawDots(Graphics pDC, Brush brush)
{
int size;
for (int i = 0; i <= 59; i++)
{
if (i % 5 == 0)
{
size = 15;
}
else
{
size = 5;
}
pDC.FillEllipse(brush,-size /2,-100-size /2,size ,size );
pDC.RotateTransform(6);
}
}
protected void DrawHourHand(Graphics pDC,Pen pen)
{
GraphicsState state = pDC.Save();
pDC.RotateTransform(360.0F * time.Hour / 12 + 30F * time.Minute / 60);
pDC.DrawLine(pen, 0, 0, 0, -50);
pDC.Restore(state);
}
protected void DrawMineteHand(Graphics pDC, Pen pen)
{
GraphicsState state = pDC.Save();
pDC.RotateTransform(360.0F * time.Minute / 60 + 6.0F * time.Second / 60);
pDC.DrawLine(pen, 0, 0, 0, -70);
pDC.Restore(state);
}
protected void DrawSecondHand(Graphics pDC, Pen pen)
{
GraphicsState state = pDC.Save();
pDC.RotateTransform(360.0F * time.Second / 60);
pDC.DrawLine(pen, 0, 0, 0, -100);
pDC.Restore(state);
}
}
}
这样简单的代码就可以实现炫酷的小东西,增加编码自信