如何在C#中将Graphics对象保存为图像?

Pri*_*moz 8 c# graphics image

我有面板和各种控件.我想将此面板的图像保存到文件中,我该怎么做?

我需要做一些截图,但我只需要在我的应用程序中使用某个面板的图像,我想在我的应用程序中点击一下按钮.

最好的问候,Primoz


编辑:我也使用此代码在此面板上绘制

            Graphics g = chartTemperature.CreateGraphics();    
            g.DrawLine(p, prevPoint, e.Location);
            prevPoint = e.Location;
Run Code Online (Sandbox Code Playgroud)

但后来我没有把它变成图像.为什么,以及如何解决这个问题?


编辑2:

namespace Grafi
{
    public partial class Form1 : Form
    {

        bool isDrawing = false;
        Point prevPoint;

        public Form1()
        {
            InitializeComponent();
        }

        private void chartTemperature_MouseDown(object sender, MouseEventArgs e)
        {
            isDrawing = true;
            prevPoint = e.Location;
        }

        private void chartTemperature_MouseMove(object sender, MouseEventArgs e)
        {
            Pen p = new Pen(Color.Red, 2); 
            if (isDrawing)
            {
                Graphics g = chartTemperature.CreateGraphics();    
                g.DrawLine(p, prevPoint, e.Location);
                prevPoint = e.Location;

                numOfMouseEvents = 0;              
            }
            p.Dispose();
        }

        private void chartTemperature_MouseUp(object sender, MouseEventArgs e)
        {
            isDrawing = false;
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

这是我在图表上绘制自定义线的绘图代码.你能帮我做正确的方法吗?

Han*_*ant 14

使用Control.DrawToBitmap()方法.例如:

    private void button1_Click(object sender, EventArgs e) {
        using (var bmp = new Bitmap(panel1.Width, panel1.Height)) {
            panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
            bmp.Save(@"c:\temp\test.png");
        }
    }
Run Code Online (Sandbox Code Playgroud)