using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace MyFormControlLibrary
{
public partial class MyDataGridView : DataGridView
{
private Image backImage;
#region Property
[Category("Custom"), Description("backgroundImage")]
public Image BackImage
{
get { return backImage; }
set { backImage = value;
base .Refresh(); // 重新加载
}
}
#endregion
protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds)
{
if (backImage != null)
{
graphics.DrawImageUnscaledAndClipped(this.backImage, gridBounds);
}
else {
//如果不添加背景图片,会导致背景污染,应该需要调用上转型解决
}
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex == -1)
{
Rectangle newRect = new Rectangle(e.CellBounds.X + 1,
e.CellBounds.Y + 1, e.CellBounds.Width - 4,
e.CellBounds.Height - 4);
using (
Brush gridBrush = new SolidBrush(this.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor),
selectedColorBrush = new SolidBrush(e.CellStyle.SelectionBackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
if (e.Value != null)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
Brushes.White, e.CellBounds.X + 2,
e.CellBounds.Y + 2, StringFormat.GenericDefault);
}
}
Rectangle border = e.CellBounds;
border.Offset(new Point(-1, -1));
e.Graphics.DrawRectangle(Pens.Cyan, border);
e.Handled = true;
}
}
else
{
Rectangle newRect = new Rectangle(e.CellBounds.X + 1,
e.CellBounds.Y + 1, e.CellBounds.Width - 4,
e.CellBounds.Height - 4);
using (
Brush gridBrush = new SolidBrush(this.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor),
selectedColorBrush = new SolidBrush(e.CellStyle.SelectionBackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
if (this.Rows[e.RowIndex].Selected)
{
e.Graphics.FillRectangle(selectedColorBrush, e.CellBounds);
}
else
{
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
}
if (e.Value != null)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
Brushes.White, e.CellBounds.X + 2,
e.CellBounds.Y + 2, StringFormat.GenericDefault);
}
}
Rectangle border = e.CellBounds;
border.Offset(new Point(-1, -1));
e.Graphics.DrawRectangle(Pens.Cyan, border);
e.Handled = true;
}
}
}
}
}
C#DataGridView绘制背景图片
最新推荐文章于 2024-04-23 17:30:16 发布