带有getPixel&的C#问题相应地设置RTF文本颜色

时间:2010-04-16 17:44:17

标签: c# colors richtextbox getpixel

Heyo,我正在搞乱将图像转换为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;

工作正常。

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

(我知道它没有正确地处理新行,但我认为我首先要解决这个问题的根源。)

由于

2 个答案:

答案 0 :(得分:1)

嗯,这部分看起来很可疑:

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

            richTextBox1.Text += "\n";
        }

       x++; 

因此,如果x是&gt; - 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中的位置取决于您在位图中的位置。

答案 1 :(得分:1)

使用+ =设置Text值会导致问题。使用+ =会导致格式化丢失,方法是重新设置Text值并指定新的字符串值。

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

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

来自MSDN:

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