[英]Paint gradient for multiple cells in TableLayoutPanel
我喜欢在tablelayoutpanel中绘制多个单元格。 我知道如何将行和列绘制为下面的普通代码:
private void tableLayoutPane1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 3 || e.Row == 4 || e.Row == 5)
{
LinearGradientBrush brush = new LinearGradientBrush(e.CellBounds, Color.White, Color.Transparent, 90F);
e.Graphics.FillRectangle(brush, e.CellBounds);
}
}
但是我想为3个单元格或行设置一个矩形渐变,而为3个单元格或多个单元格设置一个合并渐变。
这可以通过使用Paint事件而不是CellPaint事件来完成。 诀窍是找出表中每个单元格的位置。 Intellisense隐藏了两个函数( GetRowHeights()
和GetColumnWidths()
),可以获取行高和列宽,因此您可以自己计算位置:
void tlp_Paint(object sender, PaintEventArgs e) {
int[] rowHeights = tlp.GetRowHeights();
int[] colmWidths = tlp.GetColumnWidths();
int boxLeft = 0;
int boxTop = 0;
int boxRight = 0;
int boxBottom = 0;
Rectangle r = Rectangle.Empty;
for (int y = 0; y < rowHeights.Length; ++y) {
boxLeft = 0;
boxRight = 0;
boxBottom += rowHeights[y];
for (int x = 0; x < colmWidths.Length; ++x) {
boxRight += colmWidths[x];
if (x == 1 && y == 3) {
r.X = boxLeft;
r.Y = boxTop;
}
if (x == 2 && y == 5) {
r.Width = boxRight - r.Left;
r.Height = boxBottom - r.Top;
}
boxLeft += colmWidths[x];
}
boxTop += rowHeights[y];
}
if (!r.IsEmpty) {
e.Graphics.TranslateTransform(tlp.AutoScrollPosition.X,
tlp.AutoScrollPosition.Y);
using (var br = new LinearGradientBrush(
r,
Color.Red,
Color.Black,
LinearGradientMode.ForwardDiagonal)) {
e.Graphics.FillRectangle(br, r);
}
}
}
如果TableLayoutPanel控件具有任何滚动条,我已经包括了对e.Graphics.TranslateTransform
的调用。
结果:
对于任何闪烁的问题,请尝试从TableLayoutPanel继承以将其DoubleBuffered属性设置为true。
概念答案
分别设置每个单元格。 第一个单元格应类似于渐变的前三分之一,第二个单元格应类似于中间部分,依此类推。
使用System.Drawing.Color.FromArgb(int,int,int,int)或其他一种最适合的过载来手动设置颜色
您的代码结构将有所变化:
if(first cell)...
if(second cell)...
希望我能提供更多帮助,但是自从我使用winforms以来,对我来说已经很久了
另一种方法是绘制透明的单元格,并在其后以所需的渐变绘制适当大小的矩形。
对不起,我没有真实的代码。
我在下面的短代码中找到了这个问题的解决方案:
int x, y, w, h;
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 1 && e.Column == 0)
{
x = e.CellBounds.X;
y = e.CellBounds.Y;
w = e.CellBounds.Width;
h = e.CellBounds.Height;
}
if (e.Row == 2 && e.Column == 0)
{
h = h + e.CellBounds.Height;
}
if (e.Row == 1 && e.Column == 1)
{
w = w + e.CellBounds.Width;
}
if (e.Row == 3 && e.Column == 3)
{
Rectangle rc = new Rectangle(x, y, w, h);
LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.White, LinearGradientMode.Vertical);
e.Graphics.FillRectangle(brush, rc);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.