簡體   English   中英

如何以編程方式向位圖圖像添加文本? WPF

[英]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);

            }
        } 

帶有疊加文字的Kinect視頻供稿

你可以做到這一點使用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;

不幸的是,您將不得不創建一個新的BitmapSource因為我目前BitmapSource無法直接將文本寫入其中。

或者,您可以使用WriteableBitmapExhttps : //writeablebitmapex.codeplex.com/

  • 使用BitmapFactory (1)從您的框架中創建一個WriteableBitmap
  • 使用上述方法創建另一個WriteableBitmap並在其上繪制文本(2)
  • 在您的框架(1)上將文本位圖(2)

結果相同但方法不同,不確定方法2是否比較麻煩,因此是否更好。

您無需將文本繪制到圖像本身中。 在您的XAML中,只需以更高的Z順序添加一個TextBlock控件即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM