【问题标题】:Using the OnPaint() method使用 OnPaint() 方法
【发布时间】:2017-12-20 01:35:44
【问题描述】:

我正在使用this library 将二维码生成到 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();
  }
}

我在表单中有一个简单的图片框,我只想在其中生成二维码图像(如果可以在图片框中生成它)。

【问题讨论】:

标签: c# winforms qr-code onpaint


【解决方案1】:

如果您将图像放入图片框中并且只生成一次图像,那么您无需担心绘制方法(您不是在制作动画等,它只是一个 QR 码)

只需在您的表单加载中执行此操作(或在您生成图像的任何位置)

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;

【讨论】:

  • 但是库中没有返回类型为 Image 的方法,所以我可以将它分配给图片框。我也尝试了pictureBox.Invalidate()(所以它不是“表格中的任何地方”但仍然没有结果)。
  • 太棒了!现在我可以轻松地将生成的图像物理保存为位图文件。非常感谢!
【解决方案2】:

这就是我最终所做的:

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

【讨论】:

  • 虽然这样有效,但每次重新绘制表单时都会重复。我已经在上面更新了我的答案-如果您将该代码放入表单加载(或单击按钮等)中,那么您只需生成一次 QR 图像-希望对您有所帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
相关资源
最近更新 更多