【问题标题】:How could I add a text into an image in UWP?如何在 UWP 中将文本添加到图像中?
【发布时间】:2017-04-28 23:49:44
【问题描述】:

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

【问题讨论】:

标签: c# uwp win2d


【解决方案1】:

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

Install-Package Win2D.uwp

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

最后我们应该可以将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();
}

【讨论】:

  • yap:) 非常感谢你,虽然我已经解决了。
猜你喜欢
  • 2017-07-24
  • 1970-01-01
  • 2012-06-11
  • 2021-08-17
  • 2016-12-22
  • 2019-12-14
  • 1970-01-01
  • 2019-05-13
相关资源
最近更新 更多