Image background after insert into RichTextBox

2019-08-15 04:53发布

I insert images into RichTextBox from app resources. Image format PNG, background is transparent. After insert, background of image is gray. How i can set background of image to transparent?

enter image description here

My current code:

private Hashtable icons = null;

private void LoadIcons()
{
   icons = new Hashtable(3);
   icons.Add("[inf]", Properties.Resources.inf);
   icons.Add("[ok]", Properties.Resources.ok);
   icons.Add("[err]", Properties.Resources.err);
}

private void SetIcons()
{
   richTextBox.ReadOnly = false;
   foreach (string icon in icons.Keys)
   {
      while (richTextBox.Text.Contains(icon))
      {
         IDataObject tmpClibboard = Clipboard.GetDataObject();
         int index = richTextBox.Text.IndexOf(icon);
         richTextBox.Select(index, icon.Length);
         Clipboard.SetImage((Image)icons[icon]);
         richTextBox.Paste();
         Clipboard.SetDataObject(tmpClibboard);
      }
   }
   richTextBox.ReadOnly = true;
}

private void richTextBox_TextChanged(object sender, EventArgs e)
{
   SetIcons();
}

2条回答
爷的心禁止访问
2楼-- · 2019-08-15 05:10

There is no such thing as true transparency in a WinForms Control. Transparent mode inherits the default background of its parent. The way I have worked around it in the past has been to use the OnPaint event and then use the Graphics.DrawString method to position the text where I want it.

Try

Alpha blend controls

查看更多
再贱就再见
3楼-- · 2019-08-15 05:31

I have the same problem and my solution was to create new empty bitmap with your icon size and then set its background to richtextbox background color. After that, I drawed with graphics object the icon on the previous bitmap.

Here's the code:

Create a bitmap with the size of your icon (here, warning from ressource file)

Bitmap img = new Bitmap(Icons.warning.Width, Icons.warning.Height);

Create graphic object from this bitmap

Graphics graphics = Graphics.FromImage(img);

Set the background of the bitmap on richtextbox background

graphics.Clear(richTextBox.BackColor);

Then overlay your icon on the bitmap

graphics.DrawImage(Icons.warning,Point.Empty);

ps: Sorry for my bad english ;)

Peace :)

查看更多
登录 后发表回答