【发布时间】:2019-06-27 14:41:04
【问题描述】:
我正在尝试找到创建像素“网格”的最佳路径,该网格将允许基本的绘画功能,例如通过单击和移动鼠标为像素着色、选择复制、粘贴或移动的区域,或使用其他图形功能以将文本或形状渲染到像素。我查看了一些示例,例如this example,它覆盖了面板控件,并且与我想要实现的外观相似,但是绘画速度很慢,而且看起来它在绘画方面表现不佳用鼠标。是否有一个控件或我可以覆盖的控件来实现我正在寻找的功能?
以下是上述示例的示例: Sample pixel grid
以及我从上面的例子改编的代码:
public class Pixel
{
public Rectangle Bounds { get; set; }
public bool IsOn { get; set; }
public bool IsSelected { get; set; }
}
public class PixelGridControl : Panel
{
public int Columns = 99;
public int Rows = 63;
private readonly Pixel[,] pixels;
public PixelGridControl()
{
this.DoubleBuffered = true;
this.ResizeRedraw = true;
// initialize pixel grid:
pixels = new Pixel[Columns, Rows];
for (int y = 0; y < Rows; ++y)
{
for (int x = 0; x < Columns; ++x)
{
pixels[x, y] = new Pixel();
}
}
}
// adjust each column and row to fit entire client area:
protected override void OnResize(EventArgs e)
{
int top = 0;
for (int y = 0; y < Rows; ++y)
{
int left = 0;
int height = (this.ClientSize.Height - top) / (Rows - y);
for (int x = 0; x < Columns; ++x)
{
int width = (this.ClientSize.Width - left) / (Columns - x);
pixels[x, y].Bounds = new Rectangle(left, top, width, height);
left += width;
}
top += height;
}
base.OnResize(e);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
for (int y = 0; y < Rows; ++y)
{
for (int x = 0; x < Columns; ++x)
{
if (pixels[x, y].IsOn)
{
e.Graphics.FillRectangle(Brushes.Gold, pixels[x, y].Bounds);
}
else
{
ControlPaint.DrawButton(e.Graphics, pixels[x, y].Bounds,
ButtonState.Normal);
}
}
}
base.OnPaint(e);
}
// determine which button the user pressed:
protected override void OnMouseDown(MouseEventArgs e)
{
for (int y = 0; y < Rows; ++y)
{
for (int x = 0; x < Columns; ++x)
{
if (pixels[x, y].Bounds.Contains(e.Location))
{
pixels[x, y].IsOn = true;
this.Invalidate();
MessageBox.Show(
string.Format("You pressed on button ({0}, {1})",
x.ToString(), y.ToString())
);
}
}
}
base.OnMouseDown(e);
}
}
【问题讨论】:
-
为什么说 GDI+ 很慢,有什么衡量标准吗?你知道Double Buffered Graphics吗?
-
我并不是说 GDI+ 很慢,只是我在链接的示例中所指的实现。我编辑了帖子并添加了我正在测试的代码,它还利用了您所指的 DoubleBuffered 图形。从单击鼠标按钮到实际出现的矩形区域改变颜色只需要大约 2 秒。我正在尝试找出是否有不同的控制或不同的方式来实现这一点,以立即提供流畅的体验。
-
能否将demo测试项目提交到github供其他人测试?
-
原来这个方法有延迟的原因是绘制的按钮数量。转移到纯矩形格式后,延迟完全消失了。
标签: c# .net graphics drawing controls