[英]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.