繁体   English   中英

如何在WPF中直接绘制位图(BitmapSource,WriteableBitmap)?

[英]How to draw directly on bitmap (BitmapSource, WriteableBitmap) in WPF?

在GDI + Winforms中我会这样做:

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

如何使用DrawingContext在WPF中执行相同的操作?

您可以使用RenderTargetBitmap将任何WPF内容呈现为Bitmap,因为它本身就是BitmapSource 这样,您可以在WPF中使用标准绘图操作来“绘制”位图。

我看到这个问题是在2011年被问到的,但我坚信迟到总比没有好,并且唯一的其他“答案”无处可满足这个网站的正确答案标准,所以我将提供我自己的帮助找到的其他人这个问题在未来。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM