RichTextBox用表情符号/图像替换字符串

5 c# wpf richtextbox emoticons

在RichtTextBox中,我想用表情:D符号图像自动替换表情符号字符串(例如).我到目前为止工作,除了当我在现有的单词/字符串之间写出表情符号字符串时,图像会在行尾插入.

例如: hello (inserting :D here) this is a message
结果: hello this is a message ?<< image

另一个(微小的)问题是插入后的插入位置在插入之前设置.

这就是我已经得到的:

public class Emoticon
{
    public Emoticon(string key, Bitmap bitmap)
    {
        Key = key;
        Bitmap = bitmap;
        BitmapImage = bitmap.ToBitmapImage();
    }

    public string Key { get; }
    public Bitmap Bitmap { get; }
    public BitmapImage BitmapImage { get; }
}

public class EmoticonRichTextBox : RichTextBox
{
    private readonly List<Emoticon> _emoticons;

    public EmoticonRichTextBox()
    {
        _emoticons = new List<Emoticon>
        {
            new Emoticon(":D", Properties.Resources.grinning_face)
        };
    }

    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        base.OnTextChanged(e);
        Dispatcher.InvokeAsync(Look);
    }

    private void Look()
    {
        const string keyword = ":D";

        var text = new TextRange(Document.ContentStart, Document.ContentEnd);
        var current = text.Start.GetInsertionPosition(LogicalDirection.Forward);

        while (current != null)
        {
            var textInRun = current.GetTextInRun(LogicalDirection.Forward);
            if (!string.IsNullOrWhiteSpace(textInRun))
            {
                var index = textInRun.IndexOf(keyword, StringComparison.Ordinal);
                if (index != -1)
                {
                    var selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                    if (selectionStart == null)
                        continue;

                    var selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
                    var selection = new TextRange(selectionStart, selectionEnd) { Text = string.Empty };

                    var emoticon = _emoticons.FirstOrDefault(x => x.Key.Equals(keyword));
                    if (emoticon == null)
                        continue;

                    var image = new System.Windows.Controls.Image
                    {
                        Source = emoticon.BitmapImage,
                        Height = 18,
                        Width = 18,
                        Margin = new Thickness(0, 3, 0, 0)
                    };

                    // inserts at the end of the line
                    selection.Start?.Paragraph?.Inlines.Add(image);

                    // doesn't work
                    CaretPosition = CaretPosition.GetPositionAtOffset(1, LogicalDirection.Forward);
                }
            }

            current = current.GetNextContextPosition(LogicalDirection.Forward);
        }
    }
}

public static class BitmapExtensions
{
    public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        using (var stream = new MemoryStream())
        {
            bitmap.Save(stream, ImageFormat.Png);
            stream.Position = 0;

            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.DecodePixelHeight = 18;
            image.DecodePixelWidth = 18;
            image.StreamSource = stream;
            image.EndInit();
            image.Freeze();

            return image;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Yus*_*dın 2

故障线路是selection.Start?.Paragraph?.Inlines.Add(image);。您将图像附加到段落末尾。InsertBefore您应该使用或方法之一InsertAfter

但是要使用这些方法,您应该迭代内联并找到要在之前或之后插入的正确内联。这并不难。selectionStart您可以通过比较和selectionEnd以及内联的属性ElementStart来确定内联。ElementEnd

另一种棘手的可能性是您要插入的位置可能位于内联内。然后您应该拆分该内联并创建其他三个:

  • 包含插入位置之前的元素的一个
  • 包含图像的一张
  • 包含插入位置之后的元素的一个。

然后,您可以删除内联并将新的三个内联插入到正确的位置。

Wpf的RichTextBox并没有最漂亮的API。有时可能很难合作。还有另一个控件称为AvalonEdit。它比 RichTextBox 使用起来容易得多。您可能需要考虑一下。