首页 > 解决方案 > UWP RichEditBox 禁用图像调整大小

问题描述

我正在尝试构建一个本机编辑器,其中我有一个丰富的编辑框,我可以在其中插入图像。我可以从编辑器调整图像大小,如何禁用调整大小。另外在此处输入图像描述,我怎样才能取回插入的图像。

标签: uwpricheditbox

解决方案


我可以从编辑器调整图像大小,如何禁用调整大小

如果您想保持图像原始大小并插入到RichEditBox,您可以通过如下方式获取图像PixelWidthPixelHeightBitmapImage

Windows.Storage.Pickers.FileOpenPicker open = new Windows.Storage.Pickers.FileOpenPicker();
open.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
open.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
    using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))

    {
        BitmapImage image = new BitmapImage();
        await image.SetSourceAsync(fileStream);
        Test.Document.Selection.InsertImage(image.PixelWidth, image.PixelHeight, 0, VerticalCharacterAlignment.Baseline, "img", fileStream);
    }
}

另外我怎样才能得到插入的图像

从这个案例回复中,您可以从您选择的 rtf 文本中解析图片数据。然后使用正则表达式过滤可用数据。以下是您可以直接使用的完整代码。

private async void GetImage(object sender, RoutedEventArgs e)
{
    string rtf = "";
    Test.Document.Selection.GetText(TextGetOptions.FormatRtf, out rtf);
    string imageDataHex = "";
    var r = new Regex(@"pict[\s\S]+?[\r\n](?<imagedata>[\s\S]+)[\r\n]\}\\par", RegexOptions.None);
    var m = r.Match(rtf);
    if (m.Success)
    {
        imageDataHex = m.Groups["imagedata"].Value;
    }
    byte[] imageBuffer = ToBinary(imageDataHex);
    StorageFile tempfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("temppic.png", CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteBufferAsync(tempfile, imageBuffer.AsBuffer());
}

public static byte[] ToBinary(string imageDataHex)
{
    //this function taken entirely from:
    // http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter
    if (imageDataHex == null)
    {
        throw new ArgumentNullException("imageDataHex");
    }

    int hexDigits = imageDataHex.Length;
    int dataSize = hexDigits / 2;
    byte[] imageDataBinary = new byte[dataSize];

    StringBuilder hex = new StringBuilder(2);

    int dataPos = 0;
    for (int i = 0; i < hexDigits; i++)
    {
        char c = imageDataHex[i];
        if (char.IsWhiteSpace(c))
        {
            continue;
        }
        hex.Append(imageDataHex[i]);
        if (hex.Length == 2)
        {
            imageDataBinary[dataPos] = byte.Parse(hex.ToString(), System.Globalization.NumberStyles.HexNumber);
            dataPos++;
            hex.Remove(0, 2);
        }
    }
    return imageDataBinary;
}

推荐阅读