如何以编程方式将文本添加到位图图像? WPF

我正在使用Kinect传感器通过将video输入设置为位图源来显示图像上的video,如下所示。 但我的问题是如何将图像添加到图像/位图,例如分数计数器,我在下面添加了一张图片来展示我想要实现的目标。

void myKinect_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) { using (ColorImageFrame colorFrame = e.OpenColorImageFrame()) { if (colorFrame == null) return; byte[] colorData = new byte[colorFrame.PixelDataLength]; colorFrame.CopyPixelDataTo(colorData); KinectVideo.Source = BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Bgr32, null, colorData, colorFrame.Width * colorFrame.BytesPerPixel); } } 

带有叠加文字的Kinect视频Feed

您可以使用DrawingImageDrawingImage类来实现此DrawingImage

在此处输入图像描述

 var random = new Random(); var pixels = new byte[256 * 256 * 4]; random.NextBytes(pixels); BitmapSource bitmapSource = BitmapSource.Create(256, 256, 96, 96, PixelFormats.Pbgra32, null, pixels, 256 * 4); var visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { drawingContext.DrawImage(bitmapSource, new Rect(0, 0, 256, 256)); drawingContext.DrawText( new FormattedText("Hi!", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 32, Brushes.Black), new Point(0, 0)); } var image = new DrawingImage(visual.Drawing); Image1.Source = image; 

不幸的是,您将不得不创建一个新的BitmapSource因为我目前无法直接将文本写入其中。

或者你可以使用WriteableBitmapEx : https : //writeablebitmapex.codeplex.com/

  • 使用BitmapFactory (1)从您的帧创建一个WriteableBitmap
  • 使用上面的方法创建另一个WriteableBitmap并在其上绘制文本(2)
  • blit你的框架上的文本位图(2)(1)

相同但不同的方法,不确定方法2是否更好,因为它很麻烦。

您无需将文本绘制到图像本身。 在您的XAML中,只需在更高的Z顺序添加一个TextBlock控件。