分享

C# GDI 绘制自定义控件

 Cloud书屋 2012-11-20

今天用GDI+绘制一个渐变的Panel,窗体移到有的被遮盖处,比如说开始菜单以下,再移上来,就出现如图

情形。有的时候又很正常。

后来终于发现问题出在OnPaint方法里,使用渐变笔刷时是这样调用的

[c-sharp] view plaincopy?
  1. protected override void OnPaint(PaintEventArgs e)  
  2. {  
  3.     base.OnPaint(e);  
  4.     LinearGradientBrush brush = new LinearGradientBrush(e.ClipRectangle, upperColor, downColor, LinearGradientMode.Vertical);  
  5.     e.Graphics.FillRectangle(brush, e.ClipRectangle);  
  6. }  
 

当时还沾沾自喜来着,直接用了e.ClipRectangle不用自己定义Rectangle。

后来发现e.ClipRectangle指需要绘制的部分。那么,当控件被遮住不需要绘制时,e.ClipRectangle的大小自然就变化了,因此出现上述现象。因此,还是得乖乖的指定需绘制的大小。

 

另附上自定义渐变Panel的代码,如下。

[c-sharp] view plaincopy?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Drawing;  
  5. using System.Data;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Drawing.Drawing2D;  
  9. namespace MyControls  
  10. {  
  11.     public partial class MyGradientPanel :Panel  
  12.     {  
  13.         public MyGradientPanel()  
  14.         {  
  15.             InitializeComponent();  
  16.             this.SetStyle(ControlStyles.UserPaint, true);  
  17.             this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);  
  18.             this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);  
  19.             // Redraw when resized  
  20.             this.SetStyle(ControlStyles.ResizeRedraw, true);  
  21.             this.Font = SystemInformation.MenuFont;  
  22.         }  
  23.         private Color upperColor = Color.LawnGreen;  
  24.         public Color UpperColor  
  25.         {  
  26.             get { return upperColor; }  
  27.             set { upperColor = value; this.Invalidate(); }  
  28.         }  
  29.         private Color downColor = Color.LemonChiffon;  
  30.         public Color DownColor  
  31.         {  
  32.             get { return downColor; }  
  33.             set { downColor = value; this.Invalidate(); }  
  34.         }  
  35.         protected override void OnPaint(PaintEventArgs e)  
  36.         {  
  37.             base.OnPaint(e);  
  38.             Rectangle baseRectangle = new Rectangle(0, 0, this.Width, this.Height);  
  39.             using (Brush gradientBrush = new LinearGradientBrush(baseRectangle, upperColor, downColor, LinearGradientMode.Vertical))  
  40.             {  
  41.                 e.Graphics.FillRectangle(gradientBrush, baseRectangle);  
  42.             }  
  43.         }  
  44.         protected override void OnResize(EventArgs e)  
  45.         {  
  46.             base.OnResize(e);  
  47.             Invalidate();  
  48.         }  
  49.     }  
  50. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多