优化图像资源管理:1.初始化时创建512x384透明bitmap 2.中途不进行Dispose和设置为null 3.仅在控件Dispose时释放资源
This commit is contained in:
@@ -353,27 +353,61 @@ namespace JoyD.Windows.CS.Toprie
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化图像缓冲区
|
||||
/// 初始化图像缓冲区和相关图像资源
|
||||
/// </summary>
|
||||
private void InitializeImageBuffer()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 创建512*384大小的bitmap作为图像缓冲区
|
||||
// 创建512*384大小的透明bitmap作为图像缓冲区
|
||||
_imageBuffer = new Bitmap(BUFFER_WIDTH, BUFFER_HEIGHT);
|
||||
Console.WriteLine($"图像缓冲区已初始化: {BUFFER_WIDTH}x{BUFFER_HEIGHT}");
|
||||
|
||||
// 初始化缓冲区为黑色背景
|
||||
// 初始化缓冲区为透明背景
|
||||
using (Graphics g = Graphics.FromImage(_imageBuffer))
|
||||
{
|
||||
g.Clear(Color.Black);
|
||||
g.Clear(Color.Transparent);
|
||||
}
|
||||
|
||||
// 初始化InfoImage为透明bitmap
|
||||
lock (_infoImageLock)
|
||||
{
|
||||
_infoImage = new Bitmap(BUFFER_WIDTH, BUFFER_HEIGHT);
|
||||
using (Graphics g = Graphics.FromImage(_infoImage))
|
||||
{
|
||||
g.Clear(Color.Transparent);
|
||||
}
|
||||
Console.WriteLine("InfoImage已初始化为透明bitmap");
|
||||
}
|
||||
|
||||
// 初始化图像框的bitmap为透明
|
||||
if (imageBox != null && !imageBox.IsDisposed)
|
||||
{
|
||||
imageBox.Image = new Bitmap(BUFFER_WIDTH, BUFFER_HEIGHT);
|
||||
using (Graphics g = Graphics.FromImage(imageBox.Image))
|
||||
{
|
||||
g.Clear(Color.Transparent);
|
||||
}
|
||||
Console.WriteLine("图像框bitmap已初始化为透明");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"初始化图像缓冲区失败: {ex.Message}");
|
||||
// 如果初始化失败,确保_imageBuffer为null
|
||||
_imageBuffer = null;
|
||||
Console.WriteLine($"初始化图像资源失败: {ex.Message}");
|
||||
// 发生异常时释放已创建的资源
|
||||
if (_imageBuffer != null)
|
||||
{
|
||||
_imageBuffer.Dispose();
|
||||
_imageBuffer = null;
|
||||
}
|
||||
lock (_infoImageLock)
|
||||
{
|
||||
if (_infoImage != null)
|
||||
{
|
||||
_infoImage.Dispose();
|
||||
_infoImage = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,15 +615,22 @@ namespace JoyD.Windows.CS.Toprie
|
||||
}
|
||||
|
||||
// 按照用户要求:收到图像数据后,将图像保存到LastImage中
|
||||
// 不释放旧的LastImage,仅在控件Dispose时释放
|
||||
lock (_lastImageLock)
|
||||
{
|
||||
// 释放旧的LastImage资源
|
||||
if (_lastImage != null)
|
||||
// 如果是第一次设置LastImage,直接赋值
|
||||
if (_lastImage == null)
|
||||
{
|
||||
try { _lastImage.Dispose(); } catch {}
|
||||
_lastImage = newImage;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 后续更新时,使用临时变量保存新图像,然后替换引用
|
||||
Image temp = newImage;
|
||||
newImage = _lastImage;
|
||||
_lastImage = temp;
|
||||
// 注意:这里不Dispose旧图像,只在控件Dispose时统一释放
|
||||
}
|
||||
// 设置新的LastImage
|
||||
_lastImage = newImage;
|
||||
}
|
||||
|
||||
// 按照用户要求:调用更新到UI
|
||||
@@ -697,8 +738,8 @@ namespace JoyD.Windows.CS.Toprie
|
||||
{
|
||||
using (Graphics g = Graphics.FromImage(_imageBuffer))
|
||||
{
|
||||
// 清除缓冲区背景为黑色
|
||||
g.Clear(Color.Black);
|
||||
// 清除缓冲区背景为透明色
|
||||
g.Clear(Color.Transparent);
|
||||
|
||||
// 步骤1:先将LastImage绘制到全局缓冲
|
||||
if (lastImage != null)
|
||||
|
||||
Reference in New Issue
Block a user