進入智能手機時代以來,各種各樣的APP大行其道,手機上面的APP有很多流行的元素,開關按鈕個人非常喜歡,手機QQ、360衛士、金山毒霸等,都有很多開關控制一些操作,在WINFORM項目上,如果將CheckBox也改為開關按鈕,估計也會為項目增添不少新鮮感,上個月接了個私活,金額雖然只有3K,與硬件通信方面的,本人在這塊做了三年,所以做起來還是比較順手,前后用下班時間,大概花了3個星期(包含測試一個多星期)搞定,里面就重寫了部分控件,以適應項目需要。
沿襲之前的做法,本人還是喜歡直接PS好圖片后,用drawimage方法將圖片繪制到用戶控件上,啟用雙緩沖和背景透明,有些人說PS一張精美的圖片也不是很容易,需要專業的,這里提供一個好方法,讓你也可以獲取到這些圖片,其實大部分的APP都可以用解壓軟件打開,拓展名改為.zip即可,解壓出來一般里面都含有絕大部分的圖片,發現絕大部分的APP都喜歡用圖片作為背景來展示一些效果,而不是原原本本的用代碼一點點繪制。騰訊就是騰訊啊,大公司!人家的美工MM設計的圖片那真的沒得話說,絕對一流,手機QQ每次升級一個版本,都會下過來將里面的精美圖片圖標之類的提取出來,以便項目使用,(這不會算是盜版吧!)好了,開始正文吧!
第一步:先准備開關按鈕要使用到的背景圖片,一般就兩張,一張是開的,一張是關的,也可以說是開啟和關閉,如下圖:
然后將這些圖片都作為資源文件添加到項目中。
第二步:新建用戶控件
在構造函數中設置雙緩沖和背景透明以及控件大小。
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.Selectable, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.UserPaint, true); this.BackColor = Color.Transparent; this.Cursor = Cursors.Hand; this.Size = new Size(87, 27);
第三步:定義一個公共屬性,這樣的話外部就可以訪問當前選中狀態,這里也命名為Checked
bool isCheck = false; /// <summary> /// 是否選中 /// </summary> public bool Checked { set { isCheck = value; this.Invalidate(); } get { return isCheck; } }
第四步:根據當前是否選中條件分別繪制圖片,在onPaint事件中
這里為了增加多種開關樣式,還增加了CheckStyleX屬性。
protected override void OnPaint(PaintEventArgs e) { Bitmap bitMapOn = null; Bitmap bitMapOff = null; if (checkStyle == CheckStyle.style1) { bitMapOn = global::myAlarmSystem.Properties.Resources.btncheckon1; bitMapOff = global::myAlarmSystem.Properties.Resources.btncheckoff1; } else if (checkStyle == CheckStyle.style2) { bitMapOn = global::myAlarmSystem.Properties.Resources.btncheckon2; bitMapOff = global::myAlarmSystem.Properties.Resources.btncheckoff2; } else if (checkStyle == CheckStyle.style3) { bitMapOn = global::myAlarmSystem.Properties.Resources.btncheckon3; bitMapOff = global::myAlarmSystem.Properties.Resources.btncheckoff3; } else if (checkStyle == CheckStyle.style4) { bitMapOn = global::myAlarmSystem.Properties.Resources.btncheckon4; bitMapOff = global::myAlarmSystem.Properties.Resources.btncheckoff4; } else if (checkStyle == CheckStyle.style5) { bitMapOn = global::myAlarmSystem.Properties.Resources.btncheckon5; bitMapOff = global::myAlarmSystem.Properties.Resources.btncheckoff5; } else if (checkStyle == CheckStyle.style6) { bitMapOn = global::myAlarmSystem.Properties.Resources.btncheckon6; bitMapOff = global::myAlarmSystem.Properties.Resources.btncheckoff6; } Graphics g = e.Graphics; Rectangle rec = new Rectangle(0, 0, this.Size.Width, this.Size.Height); if (isCheck) { g.DrawImage(bitMapOn, rec); } else { g.DrawImage(bitMapOff, rec); } }
到此是不是完成了呢,其實不是,因為鼠標在控件上面單擊的時候,還需要改變當前的背景圖片,所以必須在Click事件中寫
private void myButtonCheck_Click(object sender, EventArgs e) { isCheck = !isCheck; this.Invalidate(); }
OK,大工告成,上圖演示效果。
源碼下載:http://files.cnblogs.com/feiyangqingyun/myButtonCheckTest.zip
附上項目截圖,歡迎提出批評改進建議!謝謝!