C# picturebox load image with an offset

10,187

Solution 1

Assuming your PNG image is imgwidth pixel wide and composed by n horizontal images, you could try this:

Image imgsrc = Image.FromFile("...."); // your PNG file
Image imgdst = new Bitmap(imgwidth/n, imgsrc.Height);
using (Graphics gr = Graphics.FromImage(imgdst))
{
    gr.DrawImage(imgsrc,
        new RectangleF(0, 0, imgdst.Width, imgdst.Height),
        new RectangleF(imgindex * imgwidth/n, 0, imgwidth/n, imgsrc.Height),
        GraphicsUnit.Pixel);
}

The idea is to create a new image (imgdst) and draw on it the part of original image you need.
With new image you can do what you please, even draw it in a picturebox.

Solution 2

You can put the PictureBox in a Panel, using the panel as your viewport. Make sure the panel's AutoScroll property is false so you don't get scroll bars appearing. Then, load the image in the PictureBox, and set it's location relative to the Panel so only the area you'd like to show is visible.

pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox1.Image = Image.FromFile(@"C:\MyPicture.png");
pictureBox1.Location = new Point(-100, -100);
Share:
10,187
さりげない告白
Author by

さりげない告白

専門の無い開発者。 国籍の無い者。 大阪で色々な仕事をやっています。

Updated on June 04, 2022

Comments

  • さりげない告白
    さりげない告白 almost 2 years

    I have a resource file (in .png format) which contain several images. They are sized and spaced in a way to where they should be relatively easy to call based on their offsets.

    I can size the picturebox to fit one image just fine; however, I don't know how to load the image based on its offsets, so I will always just get the one in the top left.

    I'm really fine with using just about any method, but haven't been able to turn up with anything useful in my searches -- since I didn't really know what to search for exactly.