C# picturebox load image with an offset

后端 未结 4 1147
时光取名叫无心
时光取名叫无心 2020-12-19 14:32

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 offse

相关标签:
4条回答
  • 2020-12-19 15:07

    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);
    
    0 讨论(0)
  • 2020-12-19 15:16

    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.

    0 讨论(0)
  • 2020-12-19 15:18

    If you just want to show a image for users, you could add the image into a label, then set the alignment property of image as you like.

    0 讨论(0)
  • 2020-12-19 15:24

    It sounds like you're tring to do something like sprites; where you have just one image loaded and then move the "view port" around to show different images.

    If that's the case, you won't be able to do this with the stock PictureBox class. You can control the sizing, but not the positioning. I think what you'd have to do is load the image, via code, and create new images based off the necessary portion of that image (using GDI+).

    0 讨论(0)
提交回复
热议问题