(UWP) Drawing on image and saving as image/byte array again

半世苍凉 提交于 2019-12-06 12:42:01

问题


I've tried a lot of different solutions in the last two days, but can't seem to find the best way.

What I want is:

1. Show image
2. Enable drawing red lines on image
3. Save image with lines

I've tried Win2D, WriteableBitmapEx, InkCanvas, normal Canvas and the Lumia Imaging SDK, but haven't had luck with at working solution. There is big chance that I'm doing it all wrong, since all those solutions don't work for me. I can't seem to find any good examples that work with UWP though. Anyone know a nice and easy way to do this?

EDIT: I'm developing in C#


回答1:


1) The first solution is using DX. You can render to the screen using Direct2D and DirectWrite and then save the rendered image to disk using the WIC API. If you are writing a Windows Store app, you can have the user select a destination file using Windows::Storage::Pickers::FileSavePicker. Here you can find a sample program.

For more complete samples about using DX in UWP to render or save images, you can refer here.

2) If you want to use pure c#, win2D is good wrapper for direct2D, which can used to draw image. With the help of RenderTargetBitmap, you can render an arbitrary UIElement into a bitmap. As about RenderTargetBitmap, here is MSDN paper, and here is good sample.

For your case, the code may look like below (You can save to file later):

XAML:

<StackPanel>
    <Button Content="Save as image source" Click="SaveImageSource_Click" />
    <Grid x:Name="RenderedGrid" Height="500"  Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <canvas:CanvasControl Draw="CanvasControl_Draw" ClearColor="CornflowerBlue"/>
    <Image x:Name="RenderedImage" Stretch="None" />
    </Grid>
</StackPanel>

C#:

private  void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
    args.DrawingSession.DrawEllipse(155, 155, 80, 30, Colors.Black, 3);
    args.DrawingSession.DrawLine(155, 155, 180, 180, Colors.Red);
}

private async void SaveImageSource_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(RenderedGrid, 500, 500);
    RenderedImage.Source = renderTargetBitmap;
}

Please let me know if anything unclear.



来源:https://stackoverflow.com/questions/33411530/uwp-drawing-on-image-and-saving-as-image-byte-array-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!