在PictureBox中绘制矩形或箭头()

时间:2015-12-31 10:12:22

标签: c# winforms

这项工作是正确的。如果我从我的系统拍照。

        pictures[idObjekt] = new Bitmap(@"C:\rectangle.png");
        picBox[idObjekt] = new PictureBox();
        picBox[idObjekt].Location = new System.Drawing.Point(25, 7);
        picBox[idObjekt].SizeMode = PictureBoxSizeMode.StretchImage;
        picBox[idObjekt].ClientSize = new Size(53, 40);
        picBox[idObjekt].Image = pictures[idObjekt];
        picBox[idObjekt].MouseDown += pictureBox1_MouseDown;
        picBox[idObjekt].MouseMove += pictureBox1_MouseMove;
        picBox[idObjekt].PreviewKeyDown += Form1_PreviewKeyDown;
        picBox[idObjekt].Tag = idObjekt;
        this.Controls.Add(this.picBox[idObjekt]);

但是当我尝试在PictureBox()中绘制一些东西时,我只看到空的PictureBox()我不知道为什么这不正常。

        pictures[idObjekt] = new Bitmap(1000, 1000, PixelFormat.Format24bppRgb);
        picBox[idObjekt] = new PictureBox();
        picBox[idObjekt].Location = new System.Drawing.Point(25, 7);
        picBox[idObjekt].SizeMode = PictureBoxSizeMode.StretchImage;
        picBox[idObjekt].ClientSize = new Size(500, 500);
        picBox[idObjekt].MouseDown += pictureBox1_MouseDown;
        picBox[idObjekt].MouseMove += pictureBox1_MouseMove;
        picBox[idObjekt].PreviewKeyDown += Form1_PreviewKeyDown;
        picBox[idObjekt].Tag = idObjekt;
        picBox[idObjekt].BackColor = Color.White;
        this.Controls.Add(this.picBox[idObjekt]);
        Graphics g = Graphics.FromImage(pictures[idObjekt]);

        // Rectangle
        int heightRec = 100;
        int widthRec = 250;
        int pozitionX = 10;
        int pozitionY = 10;

        g.DrawRectangle(Pens.White, pozitionX + 1, pozitionY + 1, widthRec - 3, heightRec - 3);
        g.DrawRectangle(Pens.Gray, pozitionX + 2, pozitionY + 2, widthRec - 3, heightRec - 3);
        g.DrawRectangle(Pens.Black, pozitionX, pozitionY, widthRec, heightRec);
        g.DrawString("The Code Project", new Font("Arial", 12, FontStyle.Italic),
        SystemBrushes.WindowText, new PointF(10, 50));

        // Arrow
        Pen p = new Pen(Color.Red, 7);
        p.EndCap = LineCap.ArrowAnchor;

        // Arrow
        Point point1 = new Point(100, 100);
        Point point2 = new Point(100, 100);
        g.DrawLine(p, point1, point2);
        g.Dispose();
        pictures[idObjekt].Dispose();

1 个答案:

答案 0 :(得分:1)

第二次,你永远不会将位图分配给PictureBox。

picBox[idObjekt].Image = pictures[idObjekt];

完成绘图后,为什么要拨打pictures[idObjekt].Dispose()? 如果您需要保留PictureBox中的图像,则不应丢弃图像。