今天用GDI+绘制一个渐变的Panel,窗体移到有的被遮盖处,比如说开始菜单以下,再移上来,就出现如图
情形。有的时候又很正常。
后来终于发现问题出在OnPaint方法里,使用渐变笔刷时是这样调用的
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
- LinearGradientBrush brush = new LinearGradientBrush(e.ClipRectangle, upperColor, downColor, LinearGradientMode.Vertical);
- e.Graphics.FillRectangle(brush, e.ClipRectangle);
- }
当时还沾沾自喜来着,直接用了e.ClipRectangle不用自己定义Rectangle。
后来发现e.ClipRectangle指需要绘制的部分。那么,当控件被遮住不需要绘制时,e.ClipRectangle的大小自然就变化了,因此出现上述现象。因此,还是得乖乖的指定需绘制的大小。
另附上自定义渐变Panel的代码,如下。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Drawing;
- using System.Data;
- using System.Text;
- using System.Windows.Forms;
- using System.Drawing.Drawing2D;
- namespace MyControls
- {
- public partial class MyGradientPanel :Panel
- {
- public MyGradientPanel()
- {
- InitializeComponent();
- this.SetStyle(ControlStyles.UserPaint, true);
- this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
- this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
-
- this.SetStyle(ControlStyles.ResizeRedraw, true);
- this.Font = SystemInformation.MenuFont;
- }
- private Color upperColor = Color.LawnGreen;
- public Color UpperColor
- {
- get { return upperColor; }
- set { upperColor = value; this.Invalidate(); }
- }
- private Color downColor = Color.LemonChiffon;
- public Color DownColor
- {
- get { return downColor; }
- set { downColor = value; this.Invalidate(); }
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
- Rectangle baseRectangle = new Rectangle(0, 0, this.Width, this.Height);
- using (Brush gradientBrush = new LinearGradientBrush(baseRectangle, upperColor, downColor, LinearGradientMode.Vertical))
- {
- e.Graphics.FillRectangle(gradientBrush, baseRectangle);
- }
- }
- protected override void OnResize(EventArgs e)
- {
- base.OnResize(e);
- Invalidate();
- }
- }
- }
|