【问题标题】:How to draw directly on bitmap (BitmapSource, WriteableBitmap) in WPF?如何在 WPF 中直接在位图(BitmapSource、WriteableBitmap)上绘制?
【发布时间】:2011-08-30 21:56:04
【问题描述】:

在 GDI+ Winforms 中我会这样做:

Bitmap b = new Bitmap(32,32);
Graphics g = Graphics.FromImage(b); 
//some graphics code...`

如何在 WPF 中使用 DrawingContext 做同样的事情?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    我看到这个问题是在 2011 年提出的,但我坚信迟到总比没有好,唯一的其他“答案”不符合这个网站的正确答案标准,所以我将提供自己的帮助来帮助任何人else 以后会发现这个问题。

    这是一个简单的示例,展示了如何绘制一个矩形并将其保存到磁盘。这样做可能有更好(更简洁的方式),但可惜的是,我在网上找到的每个链接都会导致相同的“我不知道耸耸肩”的答案。

            public static void CreateWpfImage()
            {
                int imageWidth = 100;
                int imageHeight = 100;
                string outputFile = "C:/Users/Krythic/Desktop/Test.png";
                // Create the Rectangle
                DrawingVisual visual = new DrawingVisual();
                DrawingContext context = visual.RenderOpen();
                context.DrawRectangle(Brushes.Red, null, new Rect(20,20,32,32));
                context.Close();
    
                // Create the Bitmap and render the rectangle onto it.
                RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(visual);
    
                // Save the image to a location on the disk.
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(new FileStream(outputFile, FileMode.Create));
            }
    

    据我所知,RenderTargetBitmap 被视为 ImageSource,因此您应该能够直接将其链接到 wpf 控件的图像源,而无需任何类型的转换。

    【讨论】:

      【解决方案2】:

      您可以使用RenderTargetBitmap 将任何WPF 内容呈现到位图中,因为它本身就是BitmapSource。有了这个,您可以使用standard drawing operations in WPF 在位图上“绘制”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多