为什么我不能在pictureBox中使用此代码绘制矩形?

时间:2015-04-17 09:11:30

标签: c# .net visual-studio graphics

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UTUResultWithCoordinates
{
    public partial class GetCoordinates : Form
    {
        private string sem;
        private string branch;
        private int mouseisdown = 0;
        private int recx = 0;
        private int recy = 0;
        private int mousemovingwhilepressed = 0;

        public GetCoordinates()
        {
            InitializeComponent();

        }

        public GetCoordinates(string p, string p_2)
        {
            // TODO: Complete member initialization
            InitializeComponent();
            branch = p;
            sem = p_2;
            pictureBox1.Controls.Add(pictureBox2);
            pictureBox2.Location = new Point(0, 0);
            pictureBox2.BackColor = Color.Transparent;
            pictureBox2.Width = 1191;
            pictureBox2.Height = 842;

        }

        private void GetCoordinates_Load(object sender, EventArgs e)
        {

            pictureBox1.ImageLocation =        @"D:\DotNet\UTUResultWithCoordinates\UTUResultWithCoordinates\bin\Debug\ComputerScience6.jpg";
        }






        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            if (mouseisdown == 1 && mousemovingwhilepressed==1)
            {
            System.Drawing.Graphics graphicsObj;
            graphicsObj = this.CreateGraphics();
            Pen myPen = new Pen(System.Drawing.Color.Blue, 100);
            Rectangle myRectangle = new Rectangle(recx, recy, 20, 20);
            e.Graphics.DrawRectangle(myPen, myRectangle);
         }

    }

    private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
    {
        mouseisdown = 1;
        recx = e.X;
        recy = e.Y;
        pictureBox2.CreateGraphics();

    }

    private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
    {
        label1.Text = e.X + "," + e.Y;
        mousemovingwhilepressed = 1;
        recx = e.X;
        recy = e.Y;
        pictureBox2.CreateGraphics();
    }

    private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
    {
        mousemovingwhilepressed = 0;
        mouseisdown = 0;
        pictureBox2.CreateGraphics();
    }
}

}

我创建了一个pictureBox1,其中显示了一个图像。然后我在里面创建了一个pictureBox2,这样我就可以通过拖动鼠标在该图像上绘制一个矩形。但是点击鼠标没有任何结果。错误是什么?

1 个答案:

答案 0 :(得分:2)

调用CreateGraphics不会触发PictureBox的绘制。

使用Invalidate导致重绘。

有关完整示例,请参阅:How to select an area on a PictureBox.Image with mouse in C#

附注:

  • 在构造函数以外的方法中调用InitializeControl不是一个好主意。
  • 当你需要布尔值时,使用布尔值,而不是整数。
  • 实现IDisposable(如Pen)的对象应尽可能少地创建,并在不再需要/使用时进行处理。