官网
前提
入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
如果觉得写的还行,请点个 star 支持一下吧
来都来了,点个【推荐】再走吧,谢谢
NuGet
Install-Package HZH_Controls
目录
http://www.hzhcontrols.com/blog-63.html
用处及效果
准备工作
也没什么准备的,开撸
开始
添加一个用户控件UCRotor
添加一下属性
1 private Color rotorColor = Color.Black;
2
3 public Color RotorColor
4 {
5 get { return rotorColor; }
6 set
7 {
8 rotorColor = value;
9 Refresh();
10 }
11 }
12
13 RotorAround rotorAround = RotorAround.None;
14 int jiaodu = 0;
15 public RotorAround RotorAround
16 {
17 get { return rotorAround; }
18 set
19 {
20 rotorAround = value;
21 if (value == RotorAround.None)
22 {
23 timer1.Enabled = false;
24 jiaodu = 0;
25 Refresh();
26 }
27 else
28 timer1.Enabled = true;
29 }
30 }
31 private int speed = 100;
32
33 [Description("旋转速度,100-1000,值越小 速度越快"), Category("自定义")]
34 public int Speed
35 {
36 get { return speed; }
37 set
38 {
39 if (value < 100 || value > 1000)
40 return;
41 speed = value;
42 timer1.Interval = value;
43 }
44 }
大小改变事件处理一下
1 void UCRotor_SizeChanged(object sender, EventArgs e)
2 {
3 maxWidth = Math.Min(this.Width, this.Height);
4 one = maxWidth / 10;
5 ResetPathCache();
6
7 }
然后就是重绘了
1 protected override void OnPaint(PaintEventArgs e)
2 {
3 base.OnPaint(e);
4 var g = e.Graphics;
5 this.Region = new System.Drawing.Region(lstCachePath[jiaodu]);
6 g.TranslateTransform(Width / 2, Height / 2);
7 // 旋转画板
8 g.RotateTransform(jiaodu);
9 // 回退画板x,y轴移动过的距离
10 g.TranslateTransform(-(Width / 2), -(Height / 2));
11 g.FillEllipse(new SolidBrush(rotorColor), new Rectangle((this.Width - maxWidth) / 2+5, (this.Height - maxWidth) / 2 + maxWidth / 4 + maxWidth / 8+2, maxWidth / 2-5, maxWidth / 2 - maxWidth / 4-4));
12 g.FillEllipse(new SolidBrush(rotorColor), new Rectangle(this.Width / 2, (this.Height - maxWidth) / 2 + maxWidth / 4 + maxWidth / 8+2, maxWidth / 2-5, maxWidth / 2 - maxWidth / 4-4));
13 g.FillEllipse(new SolidBrush(rotorColor), new Rectangle((this.Width - maxWidth) / 2 + maxWidth / 2 - maxWidth / 8, (this.Height - maxWidth) / 2 + maxWidth / 2 - maxWidth / 8, maxWidth / 4, maxWidth / 4));
14 g.FillEllipse(new SolidBrush(Color.FromArgb(10, Color.White)), new Rectangle((this.Width - maxWidth) / 2 + maxWidth / 2 - maxWidth / 8, (this.Height - maxWidth) / 2 + maxWidth / 2 - maxWidth / 8, maxWidth / 4, maxWidth / 4));
15
16 }
添加一个Timer用以旋转
1 private void timer1_Tick(object sender, EventArgs e)
2 {
3 if (rotorAround == RotorAround.Clockwise)
4 {
5 jiaodu += 15;
6 if (jiaodu == 180)
7 jiaodu = 0;
8 }
9 else if (rotorAround == RotorAround.Counterclockwise)
10 {
11 jiaodu -= 15;
12 if (jiaodu < 0)
13 jiaodu = 165;
14 }
15
16 Refresh();
17 }
最后的话
如果你喜欢的话,请到 https://gitee.com/kwwwvagaa/net_winform_custom_control 点个星星吧
来源:oschina
链接:https://my.oschina.net/u/4348626/blog/4281375