【问题标题】:Image background after insert into RichTextBox插入 RichTextBox 后的图像背景
【发布时间】:2025-12-05 23:55:02
【问题描述】:

我从应用程序资源中将图像插入 RichTextBox。图片格式PNG,背景透明。插入后,图像背景为灰色。如何将图像的背景设置为透明?

我当前的代码:

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();
}

【问题讨论】:

  • 创建另一个相同大小的位图。使用 Graphics.FromImage()、Graphics.Clear() 设置您想要的背景颜色(如richTextBox.BackColor)、Graphics.DrawImage() 来绘制图像。请注意,允许用户编辑 RTB 中的文本并不是一个好主意。设置 ReadOnly = true,您的问题就会消失。

标签: c# .net visual-studio


【解决方案1】:

我有同样的问题,我的解决方案是使用您的图标大小创建新的空位图,然后将其背景设置为 Richtextbox 背景颜色。之后,我用图形对象在上一个位图上绘制了图标。

代码如下:

用你的图标大小创建一个位图(这里,来自资源文件的警告)

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

从此位图创建图形对象

Graphics graphics = Graphics.FromImage(img);

在richtextbox背景上设置位图的背景

graphics.Clear(richTextBox.BackColor);

然后在位图上覆盖你的图标

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

ps:对不起我的英语不好;)

和平:)

【讨论】:

    【解决方案2】:

    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.

    试试

    Alpha blend controls

    【讨论】:

    • 我将LoadIcons() 的一部分更改为Bitmap bmp = Properties.Resources.inf; bmp.MakeTransparent(Color.FromArgb(211, 211, 211)); icons.Add("[inf]", bmp);,但这张图片的背景没有任何变化。
    最近更新 更多