【问题标题】:Drawing image from array of pixels [duplicate]从像素数组绘制图像[重复]
【发布时间】:2018-12-28 21:54:54
【问题描述】:

我正在尝试编写一个代码,该代码从索引数组中绘制一组像素,这些像素指向另一个数组(基本上是调色板)中的颜色值。除了使用图片框在屏幕上绘制图像外,我还很陌生,所以我对这样的东西没有适当的经验。根据我的研究,这段代码应该可以工作,但表格上没有任何内容。有什么想法我在这里做错了吗?

public string[] colors = new string[] { "#FFFF0000", "#FF00FF00", "#FF0000FF", "#FFFFFF00", "#FFFF00FF", "#FF00FFFF" };
public byte[] pixels = new byte[] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 };

public byte scale = 2;

public void PaintPixels()
{
    Graphics g = CreateGraphics();

    int x = 0;
    int y = 0;

    for (int p = 0;  p < pixels.Length; p++)
    {
        using (var brush = new SolidBrush(ColorTranslator.FromHtml(colors[pixels[p]])))
        {
            g.FillRectangle(brush, x, y, scale, scale);
        }

        x += scale;

        if(x > 255)
        {
            y += scale;
            x = 0;
        }
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    Width = 256 * scale;
    Height = 240 * scale;

    PaintPixels();
}

【问题讨论】:

  • 摆脱 CreateGraphics。总是错的。使用应该进行绘画的控件的绘画事件。
  • 我可以试试。上次由于某种原因不喜欢 using 语句
  • 你必须显示那个代码。
  • 您可以在应该显示调色板的控件的 Paint 事件中移动 PaintPixels()(从 int x = 0; 开始)中的代码。当然g会变成e.Graphics
  • 如 cmets 中所述,您应该使用Paint 事件或OnPaint() 方法来绘制图形,而不是CreateGraphics()。有关详细信息,请参阅标记的重复项。

标签: c# arrays winforms drawing


【解决方案1】:

只需像这样覆盖Form.OnPaint(PaintEventArgs e)

public partial class Form1 : Form
{
    private static readonly string[] colors =
        new string[] { "#FFFF0000", "#FF00FF00", "#FF0000FF", "#FFFFFF00", "#FFFF00FF", "#FF00FFFF" };
    private static readonly byte[] pixels =
        new byte[] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 };
    private static readonly byte scale = 10;

    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        for (int p = 0, x = 0, y = 0; p < pixels.Length; p++, x += scale)
        {
            if (x > 255)
            {
                x = 0;
                y += scale;
            }

            using (var brush = new SolidBrush(ColorTranslator.FromHtml(colors[pixels[p]])))
                e.Graphics.FillRectangle(brush, x, y, scale, scale);
        }
    }
}

它给出:

【讨论】:

  • 表单不需要监听自己的事件。您可以只使用 OnPaint 覆盖。另外,不要释放那个图形对象——不是你创建的。
  • @LarsTech,好点子!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-09-17
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 2022-01-10
  • 2011-10-23
相关资源
最近更新 更多