【问题标题】:C# Problem with getPixel & setting RTF text colour accordinglyC# 问题与 getPixel & 相应地设置 RTF 文本颜色
【发布时间】:2011-02-08 22:46:59
【问题描述】:

嘿嘿,我正在把图像转换成 ASCII 格式。为此,我加载图像,在每个像素上使用 getPixel(),然后将具有该颜色的字符插入到 RichTextBox 中。

        Bitmap bmBild = new Bitmap(openFileDialog1.FileName.ToString()); // valid image

        int x = 0, y = 0;

        for (int i = 0; i <= (bmBild.Width * bmBild.Height - bmBild.Height); i++)
        {
            // Ändra text här
            richTextBox1.Text += "x";
            richTextBox1.Select(i, 1);

            if (bmBild.GetPixel(x, y).IsKnownColor)
            {

                richTextBox1.SelectionColor = bmBild.GetPixel(x, y);
            }
            else
            {
                richTextBox1.SelectionColor = Color.Red;
            }


            if (x >= (bmBild.Width -1))
            {
                x = 0;
                y++;

                richTextBox1.Text += "\n";
            }

           x++; 
        }

GetPixel 确实返回了正确的颜色,但文本仅以黑色结束。如果我改变了

这个

richTextBox1.SelectionColor = bmBild.GetPixel(x, y);

到这里

richTextBox1.SelectionColor = Color.Red;

效果很好。

为什么我没有得到正确的颜色?

(我知道它没有正确执行新行,但我想我会先深入了解这个问题。)

谢谢

【问题讨论】:

    标签: c# colors richtextbox getpixel


    【解决方案1】:

    您的问题是由使用 += 设置 Text 值引起的。使用 += 会导致您的格式因重新设置 Text 值并分配新的字符串值而丢失。

    您需要更改代码以改用 Append()。

     richTextBox1.Append("x");
    richTextBox1.Append("\n");
    

    来自 MSDN:

    您可以使用此方法将文本添加到控件中的现有文本,而不是使用连接运算符 (+) 将文本连接到 Text 属性。

    【讨论】:

      【解决方案2】:

      好吧,我觉得这部分很可疑:

              if (x >= (bmBild.Width -1))
              {
                  x = 0;
                  y++;
      
                  richTextBox1.Text += "\n";
              }
      
             x++; 
      

      因此,如果 x >- width-1,则将 x 设置为 0,然后在条件之外将其递增为 1。如果您将其设置为 0,会认为它不会增加。


      编辑: 再考虑一下,为什么不在嵌套循环中迭代宽度和高度并简化一些事情。比如:

      int col = 0;
      int row = 0;
      while (col < bmBild.Height)
      {
         row = 0;
         while (row < bmBild.Width)
         {
             // do your stuff in here and keep track of the position in the RTB
             ++row;
         }
         ++col;
      }
      

      因为你把这个东西从图像的大小上赶走了,对吧? RTB 中的位置取决于您在位图中的位置。

      【讨论】:

        猜你喜欢
        • 2017-11-26
        • 1970-01-01
        • 2011-09-27
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多