如何在 UWP 中将文本添加到图像中?

How could I add a text into an image in UWP?

我想在 UWP 中将一段文字添加到图像中。当我在 win2D 中使用 Microsoft.Graphics.Canvas.Text 时,它只是创建了一个带有文本的图像。那么如何将文本添加到现有图像中呢? Thanks.Like 这个

正如@Trey 的评论,我们应该能够在 UWP 中使用 Win2d。 要安装 Win2D.uwp、运行,请在程序包管理器控制台中执行以下命令

Install-Package Win2D.uwp

我们应该能够使用 CanvasBitmap.LoadAsync 方法从流中加载位图。然后我们可以使用CanvasRenderTarget.CreateDrawingSession方法来return一个新的绘图会话,我们可以用它来绘制图像和文字到绘图会话。

最后我们应该能够将 CanvasRenderTarget 写入文件。

例如:

var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
var sourceFile = await picker.PickSingleFileAsync();
if (sourceFile == null) { return; }
var device = CanvasDevice.GetSharedDevice();
var image = default(CanvasBitmap);
using (var s = await sourceFile.OpenReadAsync())
{
    image = await CanvasBitmap.LoadAsync(device, s);
}
var offscreen = new CanvasRenderTarget(
    device, (float)image.Bounds.Width, (float)image.Bounds.Height, 96);
using (var ds = offscreen.CreateDrawingSession())
{
    ds.DrawImage(image, 0, 0);
    ds.DrawText("Hello world", 10, 10, Colors.Blue);
}
var displayInformation = DisplayInformation.GetForCurrentView();
var savepicker = new FileSavePicker();
savepicker.FileTypeChoices.Add("png", new List<string> { ".png" });
var destFile = await savepicker.PickSaveFileAsync();
using (var s = await destFile.OpenAsync(FileAccessMode.ReadWrite))
{
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, s);
    encoder.SetPixelData(
        BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Ignore,
        (uint)offscreen.Size.Width,
        (uint)offscreen.Size.Height,
        displayInformation.LogicalDpi,
        displayInformation.LogicalDpi,
        offscreen.GetPixelBytes());
    await encoder.FlushAsync();
}