我使用this library生成QRcode到WinForm应用程序,但我真的不知道如何使用OnPaint()方法。
所以我有这个:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode;
encoder.TryEncode("link to some website", out qrCode);
new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Two))
.Draw(e.Graphics, qrCode.Matrix);
base.OnPaint(e);
}
private void Form1_Load(object sender, EventArgs e)
{
this.Invalidate();
}
}
我在表单中有一个简单的pictureBox,我只想在那里生成QRcode图像(如果可以在图片框中生成它)。
如果你把你的图像放在一个图片框中并且你只生成一次你的图像,那么你不需要担心绘画方法(你不是在做动画等,它只是一个二维码)
只需在表单加载中(或在您生成图像的位置)执行此操作
mypicturebox.Image = qrCodeImage;
更新 - 附加代码以方便您的库
var bmp = new Bitmap(200, 200);
using (var g = Graphics.FromImage(bmp))
{
new GraphicsRenderer(
new FixedCodeSize(200, QuietZoneModules.Two)).Draw(g, qrCode.Matrix);
}
pictureBox1.Image = bmp;
这就是我最终做的事情:
public partial class Form1 : Form
{
public event PaintEventHandler Paint;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox_Paint);
this.Controls.Add(pictureBox1);
}
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode;
encoder.TryEncode("www.abix.dk", out qrCode);
new GraphicsRenderer(
new FixedCodeSize(200, QuietZoneModules.Two)).Draw(e.Graphics, qrCode.Matrix);
}
}