繁体   English   中英

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

[英]How to add text to a bitmap image programmatically? WPF

我正在使用Kinect传感器,通过将视频Feed设置为位图源来在图像上显示视频Feed,如下所示。 但是我的问题是如何将文本添加到图像/位图(例如计分器),我在下面添加了图片以显示我要实现的目标。

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视频供稿

你可以做到这一点使用DrawingVisualDrawingImage类:

在此处输入图片说明

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因为我目前BitmapSource无法直接将文本写入其中。

或者,您可以使用WriteableBitmapExhttps : //writeablebitmapex.codeplex.com/

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

结果相同但方法不同,不确定方法2是否比较麻烦,因此是否更好。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM