如何设置inktoolbar的笔颜色

How to set inktoolbar's pen color

如代码所示,我添加了一支圆珠笔,它支持30种颜色,但还不够。

colorSelected(Color type)是通过其他方式得到的,这里不讨论。 现在我想点击圆珠笔,使用我的 colorSelected 来绘制。 如何?谢谢

<Grid>
        <InkToolbar TargetInkCanvas="{x:Bind inkCanvas}" InitialControls="AllExceptPens" VerticalAlignment="Top">
            <InkToolbarBallpointPenButton x:Name="ballpointPen" Click="xxx_Click"/>
            <InkToolbarCustomToolButton x:Name="toolButtonColorPicker" Click="ToolButton_ColorPicker">
                <Image Height="20" Width="20" Source="ms-appx:///Assets/Palette.png"/>
                <ToolTipService.ToolTip>
                    <ToolTip Content="ColorPicker"/>
                </ToolTipService.ToolTip>
            </InkToolbarCustomToolButton>
        </InkToolbar>
        <InkCanvas x:Name="inkCanvas" Margin="0,48,0,0"/>
    </Grid>

下面的代码似乎不起作用...

private void xxx_Click(object sender, RoutedEventArgs e)
        {
            if(bUserDefinedColor)
            {
                InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
                drawingAttributes.Color = colorSelected;
                inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
            }
        }

顺便把测试工程上传到GitHubhttps://github.com/hupo376787/Test.git

这里有一个更好的解决方案,无需直接调用 UpdateDefaultDrawingAttributes

我会做的是,每当用户从您的 ColorPicker 中选择一种新颜色并点击 确定 时,将此颜色添加到 Palette InkToolbarBallpointPenButton,然后将 SelectedBrushIndex 设置为新创建颜色的索引。

您可以完全删除您的xxx_Click处理程序,并将LeftClick中的内容替换为以下内容

cpx.LeftClick += (ss, ee) =>
{
    bUserDefinedColor = true;
    colorSelected = cpx.pickerColor;

    ballpointPen.Palette.Add(new SolidColorBrush(colorSelected));
    ballpointPen.SelectedBrushIndex = ballpointPen.Palette.Count - 1;
};

就是它了!您会看到笔图标上所选颜色的视觉效果会自动反映出新颜色,从而提供出色的用户体验。


为了进一步增强用户体验,您可能还需要做两件事。

  1. 缓存添加的颜色并在应用程序启动时手动将它们添加回 Palette,以便下次用户打开应用程序时,它们仍然可用。
  2. 与其添加另一个图标来显示 ColorPicker,不如尝试将其放在 InkToolbarBallpointPenButton 的颜色弹出窗口中,这样所有颜色相关的东西都在同一个地方。位于此弹出窗口内的控件称为 InkToolbarPenConfigurationControl。您应该能够找到它的样式(参见下面的路径)并将您的 ColorPicker 添加到它。

C:\Program Files (x86)\Windows Kits\DesignTime\CommonConfiguration\Neutral\UAP.0.xxxxx.0\Generic\generic.xaml

希望对您有所帮助!