如何以编程方式向位图图像添加文本?WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21891004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add text to a bitmap image programmatically? WPF
提问by Brian J
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. 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.
我正在使用 Kinect 传感器通过将视频源设置为位图源来在图像上显示视频源,如下所示。但我的问题是如何将文本添加到图像/位图,例如分数计数器,我在下面添加了一张图片来显示我想要实现的目标。
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);
}
}


回答by Aybe
You can achieve this using DrawingVisualand DrawingImageclasses :
您可以使用DrawingVisual和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;
Unfortunately you will have to create a new BitmapSourceas there's currently no way I know of writing text directly to it.
不幸的是,您将不得不创建一个新的,BitmapSource因为我目前无法直接向其写入文本。
Alternatively you could use WriteableBitmapEx: https://writeablebitmapex.codeplex.com/
或者,您可以使用WriteableBitmapEx:https: //writeablebitmapex.codeplex.com/
- create a WriteableBitmap from your frame using
BitmapFactory(1) - create another WriteableBitmap and draw text on it using the above method (2)
- blit the text bitmap (2) over your frame (1)
- 使用
BitmapFactory(1)从您的框架创建一个 WriteableBitmap - 创建另一个 WriteableBitmap 并使用上述方法(2)在其上绘制文本
- blit 文本位图 (2) 在您的框架 (1)
Same result but different approach, not sure whether approach 2 is better as it's cumbersome.
结果相同但方法不同,不确定方法2是否更好,因为它很麻烦。
回答by NickC
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 控件。

