我正在使用 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);
}
}
最佳答案
您可以使用 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;
不幸的是,您将不得不创建一个新的 BitmapSource
,因为我目前还没有办法直接向它写入文本。
或者你可以使用WriteableBitmapEx
:https://writeablebitmapex.codeplex.com/
- 使用
BitmapFactory
从您的框架创建一个 WriteableBitmap (1) - 创建另一个WriteableBitmap 并使用上述方法(2) 在其上绘制文本
- blit 文本位图 (2) 在您的框架 (1) 上
相同的结果,不同的方法,不确定方法 2 是否更好,因为它很麻烦。
关于c# - 如何以编程方式将文本添加到位图图像? WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891004/