存储和检索Windows墨迹笔划数据

Windows支持Windows Ink 的应用可以将墨迹笔划序列化和反序列化为墨迹序列化格式 (ISF) 文件。 ISF 文件是一个 GIF 图像,其中包含所有墨迹笔划属性和行为的附加元数据。 未启用墨迹功能的应用程序可以查看带有 alpha 通道背景透明度的静态 GIF 图像。

注释

ISF 是墨迹最紧凑持久表示形式。 它可以嵌入二进制文档格式,例如 GIF 文件,也可以直接放置在剪贴板上。

可以从 Microsoft下载中心下载墨迹序列化格式(ISF)规范。

重要的API:InkCanvas、Windows.UI.Input.Inking

将墨迹笔划保存到文件

在这里,我们演示如何保存在 InkCanvas 控件上绘制的墨迹笔划。

从“保存”和从墨迹序列化格式(ISF)文件加载墨迹笔划下载此示例

  1. 首先,我们设置了 UI。

    UI 包括“保存”、“加载”和“清除”按钮,以及 InkCanvas。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel x:Name="HeaderPanel" Orientation="Horizontal" Grid.Row="0">
            <TextBlock x:Name="Header" 
                       Text="Basic ink store sample" 
                       Style="{ThemeResource HeaderTextBlockStyle}" 
                       Margin="10,0,0,0" />
            <Button x:Name="btnSave" 
                    Content="Save" 
                    Margin="50,0,10,0"/>
            <Button x:Name="btnLoad" 
                    Content="Load" 
                    Margin="50,0,10,0"/>
            <Button x:Name="btnClear" 
                    Content="Clear" 
                    Margin="50,0,10,0"/>
        </StackPanel>
        <Grid Grid.Row="1">
            <InkCanvas x:Name="inkCanvas" />
        </Grid>
    </Grid>
  1. 然后,我们设置一些基本的墨迹输入行为。

    InkPresenter 配置为将笔和鼠标中的输入数据解释为墨迹笔划(InputDeviceTypes),并声明按钮上的单击事件的侦听器。

public MainPage()
    {
        this.InitializeComponent();

        // Set supported inking device types.
        inkCanvas.InkPresenter.InputDeviceTypes =
            Windows.UI.Core.CoreInputDeviceTypes.Mouse |
            Windows.UI.Core.CoreInputDeviceTypes.Pen;

        // Listen for button click to initiate save.
        btnSave.Click += btnSave_Click;
        // Listen for button click to initiate load.
        btnLoad.Click += btnLoad_Click;
        // Listen for button click to clear ink canvas.
        btnClear.Click += btnClear_Click;
    }
  1. 最后,我们将墨迹保存在“ 保存” 按钮的单击事件处理程序中。

    FileSavePicker允许用户同时选择文件以及保存墨迹数据的位置。

    选择文件后,我们将打开IRandomAccessStream流设置为 ReadWrite。

    然后,调用 SaveAsync 将由 InkStrokeContainer 管理的墨迹笔划序列化为流。

// Save ink data to a file.
    private async void btnSave_Click(object sender, RoutedEventArgs e)
    {
        // Get all strokes on the InkCanvas.
        IReadOnlyList<InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();

        // Strokes present on ink canvas.
        if (currentStrokes.Count > 0)
        {
            // Let users choose their ink file using a file picker.
            // Initialize the picker.
            Windows.Storage.Pickers.FileSavePicker savePicker = 
                new Windows.Storage.Pickers.FileSavePicker();
            savePicker.SuggestedStartLocation = 
                Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add(
                "GIF with embedded ISF", 
                new List<string>() { ".gif" });
            savePicker.DefaultFileExtension = ".gif";
            savePicker.SuggestedFileName = "InkSample";

            // Show the file picker.
            Windows.Storage.StorageFile file = 
                await savePicker.PickSaveFileAsync();
            // When chosen, picker returns a reference to the selected file.
            if (file != null)
            {
                // Prevent updates to the file until updates are 
                // finalized with call to CompleteUpdatesAsync.
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                // Open a file stream for writing.
                IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
                // Write the ink strokes to the output stream.
                using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
                {
                    await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);
                    await outputStream.FlushAsync();
                }
                stream.Dispose();

                // Finalize write so other apps can update file.
                Windows.Storage.Provider.FileUpdateStatus status =
                    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    // File saved.
                }
                else
                {
                    // File couldn't be saved.
                }
            }
            // User selects Cancel and picker returns null.
            else
            {
                // Operation cancelled.
            }
        }
    }

注释

GIF 是保存墨迹数据的唯一文件格式。 但是, LoadAsync 方法(在下一部分中演示)支持其他格式以实现向后兼容性。

从文件加载墨迹笔划

在这里,我们演示如何从文件加载墨迹笔划,并将其呈现在 InkCanvas 控件上。

从“保存”和从墨迹序列化格式(ISF)文件加载墨迹笔划下载此示例

  1. 首先,我们设置了 UI。

    UI 包括“保存”、“加载”和“清除”按钮,以及 InkCanvas。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel x:Name="HeaderPanel" Orientation="Horizontal" Grid.Row="0">
            <TextBlock x:Name="Header" 
                       Text="Basic ink store sample" 
                       Style="{ThemeResource HeaderTextBlockStyle}" 
                       Margin="10,0,0,0" />
            <Button x:Name="btnSave" 
                    Content="Save" 
                    Margin="50,0,10,0"/>
            <Button x:Name="btnLoad" 
                    Content="Load" 
                    Margin="50,0,10,0"/>
            <Button x:Name="btnClear" 
                    Content="Clear" 
                    Margin="50,0,10,0"/>
        </StackPanel>
        <Grid Grid.Row="1">
            <InkCanvas x:Name="inkCanvas" />
        </Grid>
    </Grid>
  1. 然后,我们设置一些基本的墨迹输入行为。

    InkPresenter 配置为将笔和鼠标中的输入数据解释为墨迹笔划(InputDeviceTypes),并声明按钮上的单击事件的侦听器。

public MainPage()
    {
        this.InitializeComponent();

        // Set supported inking device types.
        inkCanvas.InkPresenter.InputDeviceTypes =
            Windows.UI.Core.CoreInputDeviceTypes.Mouse |
            Windows.UI.Core.CoreInputDeviceTypes.Pen;

        // Listen for button click to initiate save.
        btnSave.Click += btnSave_Click;
        // Listen for button click to initiate load.
        btnLoad.Click += btnLoad_Click;
        // Listen for button click to clear ink canvas.
        btnClear.Click += btnClear_Click;
    }
  1. 最后,我们在 “加载 ”按钮的单击事件处理程序中加载墨迹。

    FileOpenPicker允许用户从中同时选择文件和从中检索保存的墨迹数据的位置。

    选择文件后,我们将打开IRandomAccessStream流设置为 Read。

    然后,调用 LoadAsync读取、取消序列化和将保存的墨迹笔划加载到 InkStrokeContainer。 将笔划加载到 InkStrokeContainer 会导致 InkPresenter 立即将其呈现到 InkCanvas。

    注释

    加载新笔划之前,InkStrokeContainer 中的所有现有笔划将被清除。

// Load ink data from a file.
private async void btnLoad_Click(object sender, RoutedEventArgs e)
{
    // Let users choose their ink file using a file picker.
    // Initialize the picker.
    Windows.Storage.Pickers.FileOpenPicker openPicker =
        new Windows.Storage.Pickers.FileOpenPicker();
    openPicker.SuggestedStartLocation =
        Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
    openPicker.FileTypeFilter.Add(".gif");
    // Show the file picker.
    Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();
    // User selects a file and picker returns a reference to the selected file.
    if (file != null)
    {
        // Open a file stream for reading.
        IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
        // Read from file.
        using (var inputStream = stream.GetInputStreamAt(0))
        {
            await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(inputStream);
        }
        stream.Dispose();
    }
    // User selects Cancel and picker returns null.
    else
    {
        // Operation cancelled.
    }
}

注释

GIF 是保存墨迹数据的唯一文件格式。 但是, LoadAsync 方法支持以下格式以实现向后兼容性。

Format 说明
InkSerializedFormat (墨水序列化格式) 指定使用 ISF 持久保存的墨迹。 这是墨迹最紧凑持久表示形式。 它可以嵌入二进制文档格式,也可以直接放置在剪贴板上。
Base64InkSerializedFormat 指定通过将 ISF 编码为 base64 流来持久化的墨迹。 提供此格式,以便直接在 XML 或 HTML 文件中编码墨迹。
GIF 图 指定通过使用包含 ISF 的 GIF 文件作为嵌入到文件中的元数据来保留的墨迹。 这使得墨迹能够在没有启用墨迹功能的应用程序中被查看,并且当返回到启用墨迹功能的应用程序时,仍能保持其墨迹的完整保真度。 当在 HTML 文件中传输墨迹内容并使其可供墨迹和非墨迹应用程序使用时,此格式非常理想。
Base64Gif 指定使用 base64 编码的强化 GIF 持久保存的墨迹。 当墨迹直接在 XML 或 HTML 文件中进行编码,以便以后转换为图像时,将提供此格式。 可以使用 XML 格式生成,以包含所有墨迹信息,并用于通过可扩展样式表语言转换(XSLT)生成 HTML。

使用剪贴板复制和粘贴墨迹笔划

在这里,我们演示如何使用剪贴板在应用之间传输墨迹笔划。

为了支持剪贴板功能,内置 InkStrokeContainer 剪切和复制命令需要选择一个或多个墨迹笔划。

在本示例中,我们在使用笔杆按钮(或鼠标右键)修改输入时,将启用笔划选择功能。 有关实现笔划选择的完整示例,请参阅笔和触笔交互中的“高级处理透传输入”。

从题为“剪贴板中保存和加载墨迹笔划”的内容中下载此示例

  1. 首先,我们设置了 UI。

    UI 包括“剪切”、“复制”、“粘贴”和“清除”按钮,以及 InkCanvas 和选择画布。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel x:Name="HeaderPanel" Orientation="Horizontal" Grid.Row="0">
            <TextBlock x:Name="tbHeader" 
                       Text="Basic ink store sample" 
                       Style="{ThemeResource HeaderTextBlockStyle}" 
                       Margin="10,0,0,0" />
            <Button x:Name="btnCut" 
                    Content="Cut" 
                    Margin="20,0,10,0"/>
            <Button x:Name="btnCopy" 
                    Content="Copy" 
                    Margin="20,0,10,0"/>
            <Button x:Name="btnPaste" 
                    Content="Paste" 
                    Margin="20,0,10,0"/>
            <Button x:Name="btnClear" 
                    Content="Clear" 
                    Margin="20,0,10,0"/>
        </StackPanel>
        <Grid x:Name="gridCanvas" Grid.Row="1">
            <!-- Canvas for displaying selection UI. -->
            <Canvas x:Name="selectionCanvas"/>
            <!-- Inking area -->
            <InkCanvas x:Name="inkCanvas"/>
        </Grid>
    </Grid>
  1. 然后,我们设置一些基本的墨迹输入行为。

    InkPresenter 配置为将笔和鼠标中的输入数据解释为墨迹笔划(InputDeviceTypes)。 此处还声明了按钮上的单击事件以及用于选择功能的指针和笔划事件的侦听器。

    有关实现笔划选择的完整示例,请参阅笔和触笔交互中的“高级处理透传输入”。

public MainPage()
    {
        this.InitializeComponent();

        // Set supported inking device types.
        inkCanvas.InkPresenter.InputDeviceTypes =
            Windows.UI.Core.CoreInputDeviceTypes.Mouse |
            Windows.UI.Core.CoreInputDeviceTypes.Pen;

        // Listen for button click to cut ink strokes.
        btnCut.Click += btnCut_Click;
        // Listen for button click to copy ink strokes.
        btnCopy.Click += btnCopy_Click;
        // Listen for button click to paste ink strokes.
        btnPaste.Click += btnPaste_Click;
        // Listen for button click to clear ink canvas.
        btnClear.Click += btnClear_Click;

        // By default, the InkPresenter processes input modified by 
        // a secondary affordance (pen barrel button, right mouse 
        // button, or similar) as ink.
        // To pass through modified input to the app for custom processing 
        // on the app UI thread instead of the background ink thread, set 
        // InputProcessingConfiguration.RightDragAction to LeaveUnprocessed.
        inkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction =
            InkInputRightDragAction.LeaveUnprocessed;

        // Listen for unprocessed pointer events from modified input.
        // The input is used to provide selection functionality.
        inkCanvas.InkPresenter.UnprocessedInput.PointerPressed +=
            UnprocessedInput_PointerPressed;
        inkCanvas.InkPresenter.UnprocessedInput.PointerMoved +=
            UnprocessedInput_PointerMoved;
        inkCanvas.InkPresenter.UnprocessedInput.PointerReleased +=
            UnprocessedInput_PointerReleased;

        // Listen for new ink or erase strokes to clean up selection UI.
        inkCanvas.InkPresenter.StrokeInput.StrokeStarted +=
            StrokeInput_StrokeStarted;
        inkCanvas.InkPresenter.StrokesErased +=
            InkPresenter_StrokesErased;
    }
  1. 最后,添加笔划选择支持后,我们在 “剪切”、“ 复制”和 “粘贴 ”按钮的单击事件处理程序中实现剪贴板功能。

    对于剪切操作,我们首先在InkPresenter的InkStrokeContainer上调用CopySelectedToClipboard。

    然后,调用 DeleteSelected 以从墨迹画布中删除笔划。

    最后,从选择画布中删除所有选择笔划。

private void btnCut_Click(object sender, RoutedEventArgs e)
    {
        inkCanvas.InkPresenter.StrokeContainer.CopySelectedToClipboard();
        inkCanvas.InkPresenter.StrokeContainer.DeleteSelected();
        ClearSelection();
    }
// Clean up selection UI.
    private void ClearSelection()
    {
        var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
        foreach (var stroke in strokes)
        {
            stroke.Selected = false;
        }
        ClearDrawnBoundingRect();
    }

    private void ClearDrawnBoundingRect()
    {
        if (selectionCanvas.Children.Any())
        {
            selectionCanvas.Children.Clear();
            boundingRect = Rect.Empty;
        }
    }

对于复制操作,我们只需在 InkStrokeContainer 上调用 CopySelectedToClipboard 方法,该容器是 InkPresenter 的一部分。

private void btnCopy_Click(object sender, RoutedEventArgs e)
    {
        inkCanvas.InkPresenter.StrokeContainer.CopySelectedToClipboard();
    }

对于粘贴,我们调用 CanPasteFromClipboard ,以确保剪贴板上的内容可以粘贴到墨迹画布。

如果是,则调用PasteFromClipboard将剪贴板墨迹笔划插入InkStrokeContainer,然后InkPresenter将笔划呈现到墨迹画布。

private void btnPaste_Click(object sender, RoutedEventArgs e)
    {
        if (inkCanvas.InkPresenter.StrokeContainer.CanPasteFromClipboard())
        {
            inkCanvas.InkPresenter.StrokeContainer.PasteFromClipboard(
                new Point(0, 0));
        }
        else
        {
            // Cannot paste from clipboard.
        }
    }

主题示例

其他示例