如何在Windows Phone 8.1 WriteableBitmap 中绘制?

How to draw in Windows Phone 8.1 on WriteableBitmap?

我正在尝试使用绘图板制作应用程序。我选择 WriteableBitmapEx 用于我的目的并开始开发。我遵循了该库官方网站上的简短教程,但不幸的是我无法在位图上使用 SetPixel(...) 进行绘制。谁能帮我解决一下?

XAML代码:

<Page
x:Class="WritableBitmapApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WritableBitmapApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid>
    <Image x:Name="ImageControl"
           Source="Hobbit.png"
           Tapped="ImageControl_Tapped"
           Height="512"
           Width="350"/>
</Grid>

和 C# 代码:

public sealed partial class MainPage : Page
{
    public WriteableBitmap writeableBmp;

    public MainPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        writeableBmp = BitmapFactory.New(512, 350);
        writeableBmp.Clear(Colors.Black);
        ImageControl.Source = writeableBmp;
        writeableBmp.GetBitmapContext();
    }

    /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.
    /// This parameter is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        // TODO: Prepare page for display here.

        // TODO: If your application contains multiple pages, ensure that you are
        // handling the hardware Back button by registering for the
        // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
        // If you are using the NavigationHelper provided by some templates,
        // this event is handled for you.
    }

    private void ImageControl_Tapped(object sender, TappedRoutedEventArgs e)
    {
        var pnt = e.GetPosition(ImageControl);

        try
        {
            writeableBmp.DrawLine(0, 0, (int)pnt.X, (int)pnt.Y, Colors.White);
            ImageControl.Source = writeableBmp;
            writeableBmp.GetBitmapContext();
            writeableBmp.Invalidate();
            ImageControl.Source = writeableBmp;
        }
        catch(Exception ex)
        {

        }
    }
}

您没有处理 BitmapContext。像这样尝试:

using (writeableBmp.GetBitmapContext()) 
{
   writeableBmp.Clear();
   writeableBmp.DrawLine(0, 0, (int)pnt.X, (int)pnt.Y, Colors.White);   
} // Invalidates on exit of using block

我还建议您看一下 WriteableBitmapEx 提供的示例: https://writeablebitmapex.codeplex.com/SourceControl/latest 特别是曲线示例已经使用指针输入实现了点的绘制。它绘制样条曲线,但您可以根据需要进行调整。 \trunk\Source\WriteableBitmapExCurvesSample.WinRT\WriteableBitmapExCurvesSample.WinRT.csproj