How to draw a line across 2 pictureboxes in C#?

I'm currently tasked to make a program to draw line between 2 pictures. in the future the line will be rotated but still connected as 1 line. for now trying to make the line connect between 2 pictures first. currently using 2 panels as the pictures and big picturebox set as transparent covering both of the panel as canvas for draw the lines but when doing test run the form are blank like in the picture. My question is.

  1. How to fix this blank error? if this can be fixed then drawing the lines across pictures can be done on the big picturebox.
  2. if cant. is there any other method to draw lines / connected pictures across 2 pictureboxes? thank you very much.

I dont know the keyword to search that error. I tried using picturebox & panels but the result are same.

Form with 2 panels as pictureboxes

Form with 2 panels as pictureboxes

big picturebox covering the panel

big picturebox covering the panel

blank error result

blank error result

edit. tried splitting the 1 big picturebox for 2 images. it works for the line drawing but the blank error for the buttons below is back.

working picturebox but with blank error

Upvotes: 1

Views: 651

Answers (1)

Troy Mac1ure
Troy Mac1ure

Reputation: 647

In your main code, load the images into memory. This method keeps the files locked which can be avoided by loading them into a memorystream if desired.

    Image image1 = Image.FromFile(@"C:/Users/RPC1940/Pictures/500px.jpg");
    Image image2 = Image.FromFile(@"C:/Users/RPC1940/Pictures/500px2.jpg");

Then on the picturebox paint event draw the images onto the main canvas and paint your line over top as well. This doesn't take into account stretching, etc but should give you a start.

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        int halfWidth = pictureBox1.Width / 2;
        e.Graphics.DrawImage(image1, new Rectangle(0, 0, halfWidth, pictureBox1.Height));
        e.Graphics.DrawImage(image2, new Rectangle(halfWidth + 1, 0, halfWidth, pictureBox1.Height));
        e.Graphics.DrawLine(Pens.Black, 140, 140, 300, 300);
    }

Upvotes: 2

Related Questions