使用第三方的开源二维码生成工具:DataMatrix.net 以及 Zxing.Net
一、基本思路
普遍情况,网络上已有的例子,一般情况都是生成Bitmap位图的方式,该方式在放大、缩小、打印的情况下,会出现失真。
要求不失真的情况下,可以使用考虑矢量格式SVG。但是C#处理这种格式貌似有点难度,且需要第三方库的支持,比较麻烦。
所以保真基本思路是:用像素点的方式直接绘制。
遇到的问题:拖动,或者生成的时候,会有卡顿。
二、DataMatrix.net DMCode的绘制方法
DmtxImageEncoder.EncodeRawData 这个方法,提供了一个可以获取DMCode点阵数组的接口。
一个代码参考:
private void Refresh_DMCode(Graphics g,float Scaling) { this.panel1.Controls.Clear(); this.panel1.Refresh(); DmtxImageEncoder Die = new DmtxImageEncoder(); DataMatrix.net.DmtxImageEncoderOptions option = new DmtxImageEncoderOptions(); option.SizeIdx = DmtxSymbolSize.DmtxSymbol32x32;//形状 option.MarginSize = 0;//边距 option.ModuleSize = 2;//点阵大小 bool[,] datas = Die.EncodeRawData("W.0$PP.END", option); SolidBrush mybrush = new SolidBrush(Color.Black); int row_count = datas.GetLength(0); // 行数 int col_count = datas.GetLength(1); // 列数 // 计算每个像素块大小 int pix_width = (int)((width / col_count)* Scaling); int pix_height = (int)((height / row_count)* Scaling); for (int i = 0; i < row_count; i++) { for (int j = 0; j < col_count; j++) { // 画二维码,纵向 // 计算起始XY int x = i * pix_width; int y = j * pix_height; if (datas[i, j] == true) { g.FillRectangle(mybrush, start_x + x, start_y + y, pix_width, pix_height); } } } }
讯享网
三、Zxing.net QRCode的绘制方法
BarcodeWriter.Encode 方法,提供了一个获取像素级别点阵数组的接口。
一个代码参考:
讯享网private void Refresh_QRCode(Graphics g, float Scaling) { this.panel1.Controls.Clear(); this.panel1.Refresh(); BarcodeWriter writer = new BarcodeWriter(); writer.Format = BarcodeFormat.QR_CODE; QrCodeEncodingOptions options = new QrCodeEncodingOptions() { DisableECI = true, CharacterSet = "UTF-8", Width = (int)(width* Scaling), Height = (int)(height * Scaling), Margin = 0, QrVersion = 2, }; options.ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H; writer.Options = options; BitMatrix bm = writer.Encode("99"); for (int i = 0; i < bm.Height; i++) { BitArray ba = bm.getRow(i, null); for (int j = 0; j < ba.Size; j++) { //datas[i, j] = bm[i, j]; if (ba[j]) { //rects[bm.Height * i + j] = new Rectangle(j + RelativeY, i + RelativeX, 1, 1); g.FillRectangle(Brushes.Black, j + start_x, i + start_y, 1, 1); } } } }
参考:
C# GDI+绘制一维条码打印模糊的解决办法_weixin_的博客-CSDN博客
一个gitee:
COMTest: 一个 二维码 放大、缩小、的例子
补充DMCode改善:
// 计算每个像素块大小 double pix_width = this.Width*1.0 / col_count*1.0; double pix_height = this.Height * 1.0 / row_count * 1.0; for (int i = 0; i < row_count; i++) { for (int j = 0; j < col_count; j++) { // 画二维码,纵向 // 计算起始XY float x = (float)Math.Round(i * pix_width,1); float y = (float)Math.Round(j * pix_height,1); if (datas[i, j] == true) { g.FillRectangle(mybrush_black, RelativeX + x, RelativeY + y,(int)Math.Ceiling(pix_width), (int)Math.Ceiling(pix_height)); } else { g.FillRectangle(mybrush_white, RelativeX + x, RelativeY + y, (int)Math.Ceiling(pix_width), (int)Math.Ceiling(pix_height)); } } }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/105590.html