简体   繁体   中英

Crop and load tiled image in picturebox c#

I have a tiled image like https://i.imgsafe.org/67397f9.png and want to load its parts as image for a picture box in some mouse events. actually I want simulate button behavior.

    Bitmap source = new Bitmap(Properties.Resources.btn_close);

    public Bitmap CropImage(Bitmap srcbmp, Rectangle dstcrp)
    {
        Bitmap bmp = new Bitmap(dstcrp.Width, dstcrp.Height);
        Graphics gfx = Graphics.FromImage(bmp);
        gfx.DrawImage(srcbmp, 0, 0, dstcrp, GraphicsUnit.Pixel);
        return bmp;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
        Rectangle section = new Rectangle(new Point(0, 93), new Size(51, 30));
        pictureBox1.Image = CropImage(source, section);
    }

    private void pictureBox1_MouseLeave(object sender, EventArgs e)
    {
        Rectangle section = new Rectangle(new Point(0, 93), new Size(51, 30));
        pictureBox1.Image = CropImage(source, section);
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        Rectangle section = new Rectangle(new Point(0, 62), new Size(51, 30));
        pictureBox1.Image = CropImage(source, section);
    }

    private void pictureBox1_MouseEnter(object sender, EventArgs e)
    {
        Rectangle section = new Rectangle(new Point(0, 0), new Size(51, 30));
        pictureBox1.Image = CropImage(source, section);
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        Rectangle section = new Rectangle(new Point(0, 0), new Size(51, 30));
        pictureBox1.Image = CropImage(source, section);
    }

this is my codes that crop sections of image and load as bitmap for picture box. I think it is not very professional and may have some memory usage problems, etc... is there any simple way to do this?

2 solutions which i can think of

  1. When you first load the form you can declare 4 image/bitmap variables 1 for each Mouse State

    so instead of recrating the images again and again you can just change the image when time is right.

    var cropCoordinates= new Rectangle(new Point(0, 0), new Size(51, 30));
    var onMouseDownImage = new Bitmap(Properties.Resources.btn_close);

  2. You can have 4 different image boxes for each state (layered 1 on top of the other )and show or hide when the time is needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM