【问题标题】:how to extend draw area in Graphics.DrawImage c#如何在Graphics.DrawImage c#中扩展绘图区域
【发布时间】:2017-02-26 16:15:06
【问题描述】:

我有一个矩形 (rec),其中包含较大图像中包含较小图像的区域。我想在 Picturebox 上显示这个较小的图像。但是,我真正在做的是使用较小的图像作为图像检测器,用于 333x324 的较大图像。所以我想要做的是使用较小的图像矩形的坐标,然后绘制到图片框,从矩形的左侧开始,向外延伸 333 宽度和 324 高度。

目前我的代码有效,但它只显示用于检测目的的小图像。我希望它显示较小的图像 + 300 宽度和 + 300 高度。

我在这段代码中摆弄了几个小时,我一定是在做一些非常基本的错误。如果有人可以帮助我,我将不胜感激!

我的课程代码:

public static class Worker
{

    public static void doWork(object myForm)
    {
        //infinitely search for maps
        for (;;)
        {


            //match type signature for Threading
            var myForm1 = (Form1)myForm;

            //capture screen
            Bitmap currentBitmap = new Bitmap(CaptureScreen.capture());

            //detect map
            Detector detector = new Detector();
            Rectangle rec = detector.searchBitmap(currentBitmap, 0.1);

            //if it actually found something
            if(rec.Width != 0)
            {
                // Create the new bitmap and associated graphics object
                Bitmap bmp = new Bitmap(rec.X, rec.Y);
                Graphics g = Graphics.FromImage(bmp);

                // Draw the specified section of the source bitmap to the new one
                g.DrawImage(currentBitmap, 0,0, rec, GraphicsUnit.Pixel);

                // send to the picture box &refresh;
                myForm1.Invoke(new Action(() =>
                {
                    myForm1.getPicturebox().Image = bmp;
                    myForm1.getPicturebox().Refresh();
                    myForm1.Update();
                }));

                // Clean up
                g.Dispose();
                bmp.Dispose();

            }

            //kill
            currentBitmap.Dispose();

            //do 10 times per second
            System.Threading.Thread.Sleep(100); 

        }
    }
}

【问题讨论】:

  • 我承认我很难理解你在做什么。为什么新位图的大小是 rec.X, rec.Y ?可以展示一些整体的草图吗?

标签: c# windows forms image graphics


【解决方案1】:

如果我理解正确,rec 变量包含一个带有正确XY 的矩形,它标识了一个带有Width=333Height=324 的矩形。

所以在if 语句中,首先设置所需的大小:

rec.Width = 333;
rec.Height = 324;

然后,注意Bitmap构造函数需要宽度和高度,所以改变

Bitmap bmp = new Bitmap(rec.X, rec.Y);

Bitmap bmp = new Bitmap(rec.Width, rec.Height);

就是这样 - 其余代码可以保持现在的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    相关资源
    最近更新 更多