【发布时间】:2017-08-04 07:22:44
【问题描述】:
在 RichtTextBox 中,我想用表情图像自动替换表情字符串(例如 :D)。
到目前为止,我已经成功了,除了当我在现有单词/字符串之间写入表情符号字符串时,图像会插入到行尾。
例如:
hello (inserting :D here) this is a message
结果是:
hello this is a message ☺
另一个(小)问题是,插入后插入符号的位置设置在图像之前。
这是我已经得到的:
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;
}
}
}
【问题讨论】:
-
澄清一下,如果您使用此文本框文本运行:
This is :D a message,您会得到:This is a message ☺? -
@IanH。没错,就是这个问题
-
@rmbq 那是关于 WinForms 的。
-
@rmbq 这个不重复,因为另一个问题是关于WinForms里的RichTextBox,差别很大
标签: c# wpf richtextbox emoticons