You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 中PictureBox绘制空心图形、文字时原有加载图像消失问题求助

问题根源

你所有的绘图逻辑(包括绘制预览和最终提交绘制)都是基于全局变量bmp_image这个位图对象以及对应的Graphics实例g进行的,但你从ListBox点击加载图片时,仅修改了pictureBox1.Image的显示值,没有同步更新全局的bmp_image和g实例,原有bmp_image仍然是窗体加载时New_file()方法生成的空白白色位图。当你触发绘制操作后,代码会把pictureBox1.Image重新赋值为bmp_image,就会出现原有加载的图片消失的问题。

修复方案

修改listBox1_SelectedIndexChanged方法,加载外部图片时同步更新全局绘图对象,同时注意释放旧对象避免内存泄漏:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        var selectedImage = listBox1.SelectedItems[0].ToString();
        if (!string.IsNullOrEmpty(selectedImage) && !string.IsNullOrEmpty(currentPatientDir))
        {
            var patientFullPath = Path.Combine(currentPatientDir, selectedImage);
            // 先释放旧的GDI资源
            g?.Dispose();
            bmp_image?.Dispose();
            // 加载图片到全局位图对象
            bmp_image = new Bitmap(Image.FromFile(patientFullPath));
            // 重新创建对应全局绘图实例
            g = Graphics.FromImage(bmp_image);
            g.SmoothingMode = SmoothingMode.HighQuality;
            // 赋值给pictureBox完成显示
            pictureBox1.Image = bmp_image;
        }
    }
    catch (Exception errorMessage)
    {
        MessageBox.Show("An error has occurred: " + errorMessage.Message + "" + errorMessage.Source);
    }
}

额外优化建议

  • 窗体关闭时主动释放bmp_image、g、p等GDI资源,避免内存泄漏
  • 加载图片时可根据pictureBox1的尺寸做适配缩放,避免图片尺寸和控件尺寸不一致导致绘制坐标错位

内容的提问来源于stack exchange,提问作者H.Ka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:39:02