簡體   English   中英

為什么不能在pictureBox中用此代碼繪制矩形?

[英]Why can't I paint a rectangle with this code in pictureBox?

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,以便可以通過拖動鼠標在該圖像上繪制一個矩形。 但是單擊鼠標沒有任何反應。 有什么錯誤?

調用CreateGraphics不會觸發PictureBox的繪制。

使用Invalidate導致重畫。

有關完整示例,請參見: 如何在C#中用鼠標選擇PictureBox.Image上的區域。

旁注:

  • 在構造函數以外的方法中調用InitializeControl並不是一個好主意。
  • 當您需要布爾值時,請使用布爾值,而不是整數。
  • 實現IDisposable的對象(例如Pen)應盡可能少地創建,並在不再需要/不再使用時丟棄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM