如何在图片指定位置绘制带文本的矩形?解决Bitmap参数无效异常
问题解决:在图片上绘制黑色矩形与黄色文本并修复Bitmap初始化异常
需求与问题
需求:在指定图片的指定位置绘制黑色填充矩形,并在矩形内添加指定字号的黄色自定义文本(例如当前日期时间)。
原代码在创建Bitmap实例时抛出System.ArgumentException,错误信息为Parameter is not valid,堆栈指向Bitmap构造函数行。
原代码
DrawDateTime类代码
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Weather { public class DrawDateTime { public DrawDateTime() { string fileName = @"e:\radar_without_clouds.jpg";//... int width = 0;//... int height = 0;//... Bitmap bitmap = new Bitmap( width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); // or some other format using (Graphics graphics = Graphics.FromImage(bitmap)) { using (System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black)) { graphics.FillRectangle(myBrush, new Rectangle(0, 0, 140, 21)); // whatever // and so on... } // myBrush will be disposed at this line bitmap.Save(fileName); } // graphics will be disposed at this } } }
Form1调用代码
public Form1() { InitializeComponent(); DrawDateTime datetime = new DrawDateTime(); }
异常原因
- 参数无效:创建
Bitmap时传入的width和height值为0,Bitmap构造函数要求宽度和高度必须是大于0的整数,因此触发参数无效异常。 - 逻辑错误:原代码新建了一个空白
Bitmap,而非加载目标图片进行编辑,这不符合“在指定图片上绘制”的需求。
修复后的完整代码
DrawDateTime类(修复版)
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; namespace Weather { public class DrawDateTime { public DrawDateTime() { string targetImagePath = @"e:\radar_without_clouds.jpg"; // 加载目标图片,自动获取正确的宽高 using (Bitmap bitmap = new Bitmap(targetImagePath)) using (Graphics g = Graphics.FromImage(bitmap)) { // 开启高质量渲染,提升文本和图形效果 g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; // 定义矩形位置与尺寸(可根据需求调整) Rectangle textRect = new Rectangle(10, 10, 180, 35); // 绘制黑色填充矩形 using (SolidBrush blackBrush = new SolidBrush(Color.Black)) { g.FillRectangle(blackBrush, textRect); } // 准备要绘制的文本(当前日期时间) string displayText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 设置文本字体与颜色 using (Font textFont = new Font("微软雅黑", 12, FontStyle.Regular)) using (SolidBrush yellowBrush = new SolidBrush(Color.Yellow)) { // 设置文本在矩形内居中对齐 StringFormat format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; // 绘制文本 g.DrawString(displayText, textFont, yellowBrush, textRect, format); } // 保存修改后的图片,若需覆盖原文件需确保文件未被占用 bitmap.Save(targetImagePath); } } } }
Form1调用代码(添加异常捕获)
public Form1() { InitializeComponent(); try { new DrawDateTime(); } catch (Exception ex) { MessageBox.Show($"处理失败:{ex.Message}"); } }
关键修改说明
- 直接从目标文件加载
Bitmap,避免手动设置宽高的错误,同时满足编辑指定图片的需求。 - 移除了无效的
width和height变量,使用加载图片的固有尺寸。 - 完整实现了黑色矩形绘制与黄色文本添加的功能,支持文本居中对齐。
- 启用高质量渲染模式,优化图形和文本的显示效果。
- 所有实现
IDisposable接口的对象均用using语句包裹,确保资源被正确释放。 - 添加异常捕获,便于调试和向用户反馈错误信息。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

