如何在 WPF 中直接在位图(BitmapSource、WriteableBitmap)上绘制? [英] How to draw directly on bitmap (BitmapSource, WriteableBitmap) in WPF?

查看:90
本文介绍了如何在 WPF 中直接在位图(BitmapSource、WriteableBitmap)上绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 GDI+ Winforms 中我会这样做:

In GDI+ Winforms I would do:

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

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

How to do the same thing in WPF, with a DrawingContext?

推荐答案

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

I see this question was asked in 2011, but I firmly believe that late is better than never, and the only other "answer" nowhere meets this websites criteria for a proper answer, so I will be providing my own to help anyone else that finds this question in the future.

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

Here is a simple example that shows how to draw a rectangle and saves it to disk. There may be a better (more concise way) of doing this, but alas, every link I've found online results in the same "shrug I don't know" answer.

        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 控件的图像源,而无需任何类型的转换.

As far as I can tell, RenderTargetBitmap is considered an ImageSource, so you should be able to link that to the image source of wpf controls directly without any sort of conversions.

这篇关于如何在 WPF 中直接在位图(BitmapSource、WriteableBitmap)上绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆