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

如何使用C#中的QRCoder在生成的二维码位图下方添加文字?

实现方法

不需要修改原有二维码的生成逻辑,只需要在生成独立二维码位图后,新建一块尺寸足够容纳二维码和下方文字的空白画布,把原有二维码居中绘制在画布上半区,再在画布下半区预留的位置绘制自定义说明文字,最后输出拼接完成的新位图即可。

完整可运行实现代码

代码仅依赖System.Drawing基础图形组件,无需额外绑定特定UI框架,在Windows桌面应用、跨平台服务端场景均可正常运行。直接在原有QRCoder二维码生成逻辑后追加位图绘制代码即可:

// 原有QRCoder生成二维码的逻辑直接保留
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("This is QR Code", QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);

// 新增:二维码下方添加自定义文字的逻辑
// 可根据实际需求调整的配置项
string tipText = "扫码获取更多信息";
Font textFont = new Font("微软雅黑", 14f, FontStyle.Regular);
int sidePadding = 20; // 画布四周的统一内边距
int qrTextGap = 30; // 二维码和下方文字的垂直间距

// 测量文字尺寸,计算画布总大小,避免内容被裁切
using (Graphics tempMeasureGraphics = Graphics.FromImage(qrCodeImage))
{
    SizeF textSize = tempMeasureGraphics.MeasureString(tipText, textFont);
    int totalWidth = (int)Math.Max(qrCodeImage.Width, textSize.Width) + sidePadding * 2;
    int totalHeight = (int)Math.Round(sidePadding * 2 + qrCodeImage.Height + qrTextGap + textSize.Height);

    // 创建白色背景的新画布
    Bitmap finalQrImage = new Bitmap(totalWidth, totalHeight);
    using (Graphics drawGraphics = Graphics.FromImage(finalQrImage))
    {
        drawGraphics.Clear(Color.White);
        // 开启文字抗锯齿,避免渲染发虚
        drawGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

        // 水平居中绘制原有二维码
        int qrPosX = (totalWidth - qrCodeImage.Width) / 2;
        int qrPosY = sidePadding;
        drawGraphics.DrawImage(qrCodeImage, qrPosX, qrPosY);

        // 水平居中绘制下方说明文字
        int textPosX = (int)((totalWidth - textSize.Width) / 2);
        int textPosY = (int)(sidePadding + qrCodeImage.Height + qrTextGap);
        drawGraphics.DrawString(tipText, textFont, Brushes.Black, textPosX, textPosY);
    }
}

// 释放临时生成的原始二维码位图资源
qrCodeImage.Dispose();

常见效果调整方式

  • 若需修改文字颜色,只需把Brushes.Black替换为自定义颜色的Brush对象即可
  • 若需要给二维码增加白边、圆角、中心嵌入品牌logo的效果,可在二维码绘制步骤前补充对应位图处理逻辑,不会影响后续的文字绘制流程
  • 跨平台部署(Linux、MacOS)时,需通过Nuget安装System.Drawing.Common组件,同时配置对应平台的图形依赖库,避免位图初始化报错
  • 高DPI场景下若出现文字拉伸模糊,可在初始化绘图对象后,将drawGraphics.DpiX、drawGraphics.DpiY设置为和目标显示设备匹配的DPI值即可

内容的提问来源于stack exchange,提问作者J.W

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 15:36:09