C# 图形对象无法引用非静态字段方法或属性
非静态字段、方法或属性“Form1.pic”不能被字段初始值设定项引用,在这种情况下,我猜是“private Graphics gfx”。虽然pic可以在整个代码中成功引用,但它不能作为公共分部类中的变量正确引用:C# 图形对象无法引用非静态字段方法或属性,c#,winforms,C#,Winforms,非静态字段、方法或属性“Form1.pic”不能被字段初始值设定项引用,在这种情况下,我猜是“private Graphics gfx”。虽然pic可以在整个代码中成功引用,但它不能作为公共分部类中的变量正确引用: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.OCR;
using Emgu.CV.Structure;
namespace Acatek_Text_Extractor_Project
{
public partial class Form1 : Form
{
private Tesseract OCRz = new Tesseract("tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY);
private Bitmap pic = new Bitmap(481, 300);
// All of the code in this line below is correct except for "pic" being underlined for the supposed error.
private Graphics gfx = Graphics.FromImage(pic);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
gfx.CopyFromScreen(new Point(this.Location.X + PictureBox.Location.X + 4, this.Location.Y + PictureBox.Location.Y + 30), new Point(0, 0), pic.Size);
PictureBox.Image = pic;
}
private void ExtractButton_Click(object sender, EventArgs e)
{
OCRz.Recognize(new Image<Bgr, byte>(pic));
ResultBox.Text = OCRz.GetText;
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用Emgu.CV;
使用Emgu.Util;
使用Emgu.CV.OCR;
使用Emgu.CV.Structure;
名称空间Acatek_文本_提取器_项目
{
公共部分类Form1:Form
{
private Tesseract OCRz=新的Tesseract(“Tesseract数据”,“eng”,Tesseract.OcrEngineMode.OEM(仅限Tesseract));
私有位图pic=新位图(481300);
//下面这一行中的所有代码都是正确的,除了“pic”被下划线表示假定的错误。
私有图形gfx=Graphics.FromImage(pic);
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
}
私有无效计时器1_刻度(对象发送方,事件参数e)
{
gfx.CopyFromScreen(新点(this.Location.X+PictureBox.Location.X+4,this.Location.Y+PictureBox.Location.Y+30),新点(0,0),图片大小);
PictureBox.Image=pic;
}
私有无效提取按钮\u单击(对象发送者,事件参数e)
{
OCRz.识别(新图像(pic));
ResultBox.Text=OCRz.GetText;
}
}
}
只需将gfx
定义放在原处,但在构造函数中实例化它:
private Graphics gfx;
gfx = Graphics.FromImage(pic);
然后在构造函数中:
private Graphics gfx;
gfx = Graphics.FromImage(pic);
为什么我们要将图形gfx
提取为字段
处理它
private void timer1_Tick(object sender, EventArgs e)
{
//DONE: we should Dispose Graphics to realease HDC unmanaged resource
using (Graphics gfx = Graphics.FromImage(pic))
{
gfx.CopyFromScreen(new Point(Location.X + PictureBox.Location.X + 4,
Location.Y + PictureBox.Location.Y + 30),
new Point(0, 0),
pic.Size);
PictureBox.Image = pic;
}
}