Search code examples
c#winformsqr-codeonpaint

Using the OnPaint() method


I am using this library to generate QRcode into a WinForm application, but I don't really know how to take use of the OnPaint() method.

So I have this:

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();
  }
}

I have a simple pictureBox in the form and I just want to generate the QRcode image in there (if it is possible to generate it in a picturebox).


Solution

  • If you're putting your image in a picturebox and you're only producing your image once, then you don't need to worry about the paint method (you're not doing an animation etc, it's just a QR code)

    Just do this in your form load (or where ever you produce your image)

    mypicturebox.Image = qrCodeImage;
    

    Update - additional code to facilitate your library

        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;