[英]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);
}
}
你可以做到这一点使用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
因为我目前BitmapSource
无法直接将文本写入其中。
或者,您可以使用WriteableBitmapEx
: https : //writeablebitmapex.codeplex.com/
BitmapFactory
(1)从您的框架中创建一个WriteableBitmap 结果相同但方法不同,不确定方法2是否比较麻烦,因此是否更好。
您无需将文本绘制到图像本身中。 在您的XAML中,只需以更高的Z顺序添加一个TextBlock控件即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.