简体   繁体   English

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

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

I'm using a Kinect sensor to show a video feed on an image by setting the video feed as bitmap source like shown below. 我正在使用Kinect传感器,通过将视频Feed设置为位图源来在图像上显示视频Feed,如下所示。 But my question is how would I add text to the image/bitmap for example a score counter, I added a picture below to show what I'm trying to achieve. 但是我的问题是如何将文本添加到图像/位图(例如计分器),我在下面添加了图片以显示我要实现的目标。

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

You can achieve this using DrawingVisual and DrawingImage classes : 你可以做到这一点使用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;

Unfortunately you will have to create a new BitmapSource as there's currently no way I know of writing text directly to it. 不幸的是,您将不得不创建一个新的BitmapSource因为我目前BitmapSource无法直接将文本写入其中。

Alternatively you could use WriteableBitmapEx : https://writeablebitmapex.codeplex.com/ 或者,您可以使用WriteableBitmapExhttps : //writeablebitmapex.codeplex.com/

  • create a WriteableBitmap from your frame using BitmapFactory (1) 使用BitmapFactory (1)从您的框架中创建一个WriteableBitmap
  • create another WriteableBitmap and draw text on it using the above method (2) 使用上述方法创建另一个WriteableBitmap并在其上绘制文本(2)
  • blit the text bitmap (2) over your frame (1) 在您的框架(1)上将文本位图(2)

Same result but different approach, not sure whether approach 2 is better as it's cumbersome. 结果相同但方法不同,不确定方法2是否比较麻烦,因此是否更好。

You don't need to draw the text into the image itself. 您无需将文本绘制到图像本身中。 In your XAML just add a TextBlock control at a higher Z order. 在您的XAML中,只需以更高的Z顺序添加一个TextBlock控件即可。

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

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