【问题标题】:How do I write text on WriteableBitmap?如何在 WriteableBitmap 上写文本?
【发布时间】:2020-02-02 00:37:15
【问题描述】:

现在我正在编写游戏代码,我需要在 WriteableBitmap 上绘制文本;如何在不从 WritableBitmap 转换为 Bitmap 再到 WriteableBitmap 的情况下做到这一点?我已经在寻找解决方案,但所有这些都会减慢我的游戏速度或需要 Silverlight 之类的东西才能工作。

类似这样的:

public class ResourceCounter : UIElement
{

    public ResourceCounter()
    {
        RenderBounds = new Bound(new Point(0, 0),
                                 new Point(600, 30));
    }

    private string goldAmt;
    private string woodAmt;
    private string stoneAmt;

    public override void Tick()
    {
        goldAmt = GlobalResources.Gold.ToString();
        woodAmt = GlobalResources.Wood.ToString();
        stoneAmt = GlobalResources.Stone.ToString();
    }

    public override void Draw(WriteableBitmap bitmap)
    {
        bitmap.FillRectangle(RenderBounds.A.X,
        Renderbounds.A.Y,
        Renderbounds.B.X,
        Renderbounds.B.Y,
        Colors.DarkSlateGray);
        bitmap.DrawString("text", other parameters...");
    }

}

【问题讨论】:

    标签: c# wpf writeablebitmap writeablebitmapex


    【解决方案1】:

    您可以在 Bitmap 和 BitmapSource 之间共享像素缓冲区

    var writeableBm1 = new WriteableBitmap(200, 100, 96, 96, 
        System.Windows.Media.PixelFormats.Bgr24, null);
    
    var w = writeableBm1.PixelWidth;
    var h = writeableBm1.PixelHeight;
    var stride = writeableBm1.BackBufferStride;
    var pixelPtr = writeableBm1.BackBuffer;
    
    // this is fast, changes to one object pixels will now be mirrored to the other 
    var bm2 = new System.Drawing.Bitmap(
        w, h, stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, pixelPtr);
    
    writeableBm1.Lock();
    
    // you might wanna use this in combination with Lock / Unlock, AddDirtyRect, Freeze
    // before you write to the shared Ptr
    using (var g = System.Drawing.Graphics.FromImage(bm2))
    {
        g.DrawString("MyText", new Font("Tahoma", 14), System.Drawing.Brushes.White, 0, 0);
    }
    
    writeableBm1.AddDirtyRect(new Int32Rect(0, 0, 200, 100));
    writeableBm1.Unlock();
    

    【讨论】:

    • 有趣的是,PixelFormats.Bgr24 匹配 Format24bppRgb,同时还有 PixelFormats.Rgb24
    • 嗯,这很奇怪。我会记住这一点。说到像素格式,你知道 BitmapFactory.New(x, y) 创建的是什么格式吗?我得到了要显示的文本,但它看起来垂直拉伸并且颜色非常糟糕。编辑:我应该澄清我需要使用 WriteableBitmapEx。
    • 没关系,我发现它使用了 Format32bppArgb;有道理,因为我在 WriteableBitmapEx 网站上看到它使用 32 位颜色。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多