如何在WriteableBitmap上的Windows Phone 8.1中绘图?

时间:2015-09-22 05:56:58

标签: c# xaml windows-phone-8.1 writeablebitmapex

我正在尝试使用绘图板制作应用程序。我选择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)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

您没有处理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 特别是曲线样本已经使用指针输入实现了点的绘制。它绘制样条曲线,但您可以根据需要进行调整。 \树干\源\ WriteableBitmapExCurvesSample.WinRT \ WriteableBitmapExCurvesSample.WinRT.csproj