開発中のアプリケーションに RichTextBox コントロールがあり、これを ToolBar と共に使用してリッチ テキスト エディターを作成しています。私が実装した機能の 1 つは、ユーザーが画像を挿入できる機能です。この時点で、RichTextBox からの出力が RTF であることに注意してください。
ユーザーが画像を挿入するとき、次のコードを使用して画像をドキュメントに追加し、ResizeAdorner (ここではRichTextBox Resizing Adornerの例) を画像に追加して、ユーザーがサイズを変更できるようにします。ユーザーがドキュメントを保存してロードすると、イメージのサイズが正しく保持されます。
private void BtnInsertImage_OnClick(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.Filter = "Image files (*.png;*.jpg;*.jpeg;*.gif;*.bmp)|*.png;*.jpg;*.jpeg;*.gif;*.bmp";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
ofd.Title = "Insert Image";
if (ofd.ShowDialog() == true)
{
BitmapImage bitmap = new BitmapImage(new Uri(ofd.FileName, UriKind.RelativeOrAbsolute))
{
CacheOption = BitmapCacheOption.OnLoad
};
Image image = new Image();
image.IsEnabled = true;
image.Source = bitmap;
image.Width = bitmap.Width;
image.Height = bitmap.Height;
image.Loaded += this.ImageOnLoaded;
image.Stretch = Stretch.Uniform;
InlineUIContainer container = new InlineUIContainer(image, this.rtbEditor.Selection.Start);
Paragraph paragraph = new Paragraph(container);
var doc = this.rtbEditor.Document;
doc.Blocks.Add(paragraph);
}
}
private void ImageOnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var img = sender as Image;
if (img != null)
{
var al = AdornerLayer.GetAdornerLayer(img);
if (al != null)
{
al.Add(new ResizingAdorner(img));
}
}
}
問題と質問は、ドキュメントが読み込まれたときに、ドキュメント内の画像に ResizingAdorner を追加する方法がわからないことです。添付プロパティを使用してドキュメントのコンテンツをロードしています。以下のコードは、ドキュメントをロードする部分です。
var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Load(stream, DataFormats.Xaml);
richTextBox.Document = doc;
ロードされたドキュメント内の任意の画像に ResizingAdorner を追加する方法を教えてください。