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

如何使用C#及ZXing库生成圆形二维码?

生成圆形模块的二维码(C# + ZXing)

ZXing库默认的BitmapRenderer会绘制方形二维码模块,要实现你需要的圆形模块样式,必须自定义渲染器替换默认的方形绘制逻辑。以下是完整实现方案:

自定义圆形BitmapRenderer

创建继承自BitmapRenderer的类,重写Render方法,把每个黑色模块替换为圆形:

using System.Drawing;
using ZXing;
using ZXing.Common;
using ZXing.Windows.Compatibility;

public class CircleBitmapRenderer : BitmapRenderer
{
    public override Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
    {
        var width = matrix.Width;
        var height = matrix.Height;
        var bitmap = new Bitmap(width, height);
        var moduleSize = options.Width / width; // 计算单个模块的尺寸

        using (var g = Graphics.FromImage(bitmap))
        {
            g.Clear(Background);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    if (matrix[x, y])
                    {
                        // 计算圆形居中位置与半径,避免边缘溢出
                        float posX = x * moduleSize + moduleSize / 2;
                        float posY = y * moduleSize + moduleSize / 2;
                        float radius = moduleSize * 0.45f;

                        using (var brush = new SolidBrush(Foreground))
                        {
                            g.FillEllipse(brush, posX - radius, posY - radius, radius * 2, radius * 2);
                        }
                    }
                }
            }
        }

        // 按设定尺寸缩放最终图片
        if (options.Width != width || options.Height != height)
        {
            var scaledBitmap = new Bitmap(bitmap, options.Width, options.Height);
            bitmap.Dispose();
            return scaledBitmap;
        }

        return bitmap;
    }
}

修改原生成方法

将原代码中的默认渲染器替换为自定义的圆形渲染器:

public Bitmap GenerateQR(string text)
{
    if (string.IsNullOrWhiteSpace(text))
        return null;

    BarcodeWriter br = new BarcodeWriter();
    EncodingOptions encodingOptions = new EncodingOptions()
    {
        Width = 300,
        Height = 300,
        Margin = 1,
        PureBarcode = false,
    };

    encodingOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    br.Options = encodingOptions;
    br.Format = BarcodeFormat.QR_CODE;

    // 启用自定义圆形渲染器
    br.Renderer = new CircleBitmapRenderer()
    {
        Foreground = Color.Black,
        Background = Color.White,
    };

    return br.Write(text);
}

关键细节说明

  • 半径比例:radius = moduleSize * 0.45f是经验值,既保证圆形不超出模块边界,又能维持足够的识别清晰度,可根据需求微调。
  • 抗锯齿优化:开启AntiAlias能让圆形边缘更平滑,提升视觉效果。
  • 错误校正:保留ErrorCorrectionLevel.H高容错级别,确保二维码即使模块视觉变形也能正常识别。

内容的提问来源于stack exchange,提问作者Japv

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:22:06