如何从C#中的Graphics对象获取位图/图像?

dat*_*ayo 10 .net c# graphics system.drawing bitmap

我想知道Graphics对象绘制一些东西的缓冲区的中间状态.如何获取位图或正在绘制的图像?

Cod*_*ray 8

我不确定我是否明白你的要求,因为你的问题很不清楚.

如果您想知道如何将Graphics对象的内容保存到位图,那么答案是没有直接的方法来执行此操作.在Graphics对象上绘图是单向操作.

更好的选择是创建一个新Bitmap对象,获取Graphics该位图的对象,并直接绘制到该对象上.以下代码是您如何执行此操作的示例:

// Create a new bitmap object
using (Bitmap bmp = new Bitmap(200, 300))
{
    // Obtain a Graphics object from that bitmap
    using (Graphics g = Graphics.FromImage(bmp))
    {
        // Draw onto the bitmap here
        // ....
        g.DrawRectangle(Pens.Red, 10, 10, 50, 50);
    }

    // Save the bitmap to a file on disk, or do whatever else with it
    // ...
    bmp.Save("C:\\MyImage.bmp");
}
Run Code Online (Sandbox Code Playgroud)


小智 1

您看过这篇 MSDN 文章吗?它描述了 Bitmap 类,该类是用于处理由像素数据定义的图像的对象。System.Drawing.Image 为其提供了附加功能。华泰