[英]Panel control gradient fill not working
我有一個面板控件,我想用漸變填充。 我有以下代碼:
Brush brush = new LinearGradientBrush(pnlBody.ClientRectangle, Color.Black, Color.White, LinearGradientMode.ForwardDiagonal);
pnlBody.CreateGraphics().FillRectangle(brush, pnlBody.ClientRectangle);
但這沒有效果。 如果我將pnlBody替換為表格,那么它將為表格上色,但不會為面板着色。 有什么想法我做錯了嗎? 謝謝!
Panel控件將使用其Paint事件繪制自身。 通過使用CreateGraphics()可以擦除您繪制的所有內容。 您將需要使用其Paint事件。 但是,這將產生閃爍,您將首先看到它繪制背景。 面板還經過優化,可以用作容器控件,且具有低影響的繪制開銷,您將看到它在調整大小時不會重新繪制自身。 將其錨定在右側或底部並調整表單大小時出現問題。
要解決這些問題,您應該從Panel派生您自己的類。 在您的項目中添加一個新類,並粘貼以下代碼:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class GradientPanel : Panel {
public GradientPanel() {
this.ResizeRedraw = true;
}
protected override void OnPaintBackground(PaintEventArgs e) {
using (var brush = new LinearGradientBrush(this.ClientRectangle,
Color.Black, Color.White, LinearGradientMode.ForwardDiagonal)) {
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
}
protected override void OnScroll(ScrollEventArgs se) {
this.Invalidate();
base.OnScroll(se);
}
}
構建+構建。 將新控件從工具箱的頂部拖放到您的窗體上,替換原來的面板。 您可以通過添加選擇漸變開始和結束顏色的屬性來獲得創造力,從而產生可以在其他項目中重用的更通用的控件。 請避免使面板顯示滾動條,因為Windows具有“拖動時顯示窗口內容”功能,因此無法使滾動看起來像樣。 效果有點類似於pogo。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.