如何在图像上绘制文本并使用UWP保存(适用于Windows 10)

时间:2017-09-20 15:34:19

标签: c# uwp draw

我想在UWP(适用于Windows 10)的模板图像上绘制文本,然后能够保存图像(以便用户可以打印或共享它)。

我玩过画布控件,甚至是nuget的Win2D软件包。任何有关最佳方法的建议都表示赞赏。我离开的示例代码如下。

XAML

<Page
x:Class="DrawTextExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DrawTextExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml"
mc:Ignorable="d">

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Name="btnSaveImage" Content="Save the image" Margin="10" Click="btnSaveImage_Click" />

    <Grid Name="MyCreatedImage">
        <Image Name="imgName" Stretch="UniformToFill" Source="Assets/HelloMyNameIs.jpg" />
        <TextBlock Name="lblName" Text="McFly" Margin="20,100,20,20" FontSize="36"/>
    </Grid>
</StackPanel>

代码背后

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace DrawTextExample {
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void btnSaveImage_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
            var bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(MyCreatedImage);
        }
    }
}

图片(HelloMyNameIs.jpg) Hello my name is

1 个答案:

答案 0 :(得分:2)

  

我想在UWP(适用于Windows 10)的模板图像上绘制文本,然后能够保存图像(以便用户可以打印或共享它)。

根据您的代码段,您尝试使用符合您要求的RenderTargetBitmap。此类可以将ImageTextBlock一起呈现为一个图像。您的代码段只是缺少保存。您可以按如下方式保存渲染图像:

private async void btnSaveImage_Click(object sender, RoutedEventArgs e)
{
    RenderTargetBitmap bitmap = new RenderTargetBitmap();
    await bitmap.RenderAsync(MyCreatedImage);

    var pixelBuffer = await bitmap.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();
    var displayInformation = DisplayInformation.GetForCurrentView();
    StorageFolder pictureFolder = KnownFolders.SavedPictures;
    var file = await pictureFolder.CreateFileAsync("test2.jpg", CreationCollisionOption.ReplaceExisting);
    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                             BitmapAlphaMode.Premultiplied,
                             (uint)bitmap.PixelWidth,
                             (uint)bitmap.PixelHeight,
                             displayInformation.RawDpiX,
                             displayInformation.RawDpiY,
                             pixels);
        await encoder.FlushAsync();
    }
}

您也可以尝试使用可能推荐的Win2D。您可以根据需要绘制图像,绘制文本和绘制形状。它提供了CanvasBitmap.SaveAsync方法来保存结果。例如,以下演示展示了如何在图像上绘制文本并将其保存到图片文件夹中。

Uri imageuri = new Uri("ms-appx:///Assets/HelloMyNameIs.jpg");
StorageFile inputFile = await StorageFile.GetFileFromApplicationUriAsync(imageuri);
BitmapDecoder imagedecoder;
using (var imagestream = await inputFile.OpenAsync(FileAccessMode.Read))
{
    imagedecoder =await BitmapDecoder.CreateAsync(imagestream);
}  
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, imagedecoder.PixelWidth, imagedecoder.PixelHeight, 96);
using (var ds = renderTarget.CreateDrawingSession())
{
    ds.Clear(Colors.White);
    CanvasBitmap image = await CanvasBitmap.LoadAsync(device, inputFile.Path, 96);
    ds.DrawImage(image);
    ds.DrawText(lblName.Text, new System.Numerics.Vector2(150, 150), Colors.Black);
}
string filename = "test1.png";
StorageFolder pictureFolder = KnownFolders.SavedPictures;
var file = await pictureFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
}

如果您想在图片上绘制个性文字,可以考虑使用InkCanvasDrawInk。您可以参考this thread详细信息。