Search code examples
c#wpfsystem.drawingbitmapimage

Repeating the image in horizontal position ( C# Drawing )


am using c#

am having a bitmap image like below

alt text

i want create a repeated image like below in horizontal position to get repeted continous image for some given width. i meant i like to draw repeated image like below from the above single bitmap (In simple words,in html we can have a image and set repeat X to get the repeated image.like that) how i can do this in c#.

alt text

so that i can draw a new bitmap in my application. How to do this.?


Solution

  • You can do it like this:

    Bitmap myImage = new Bitmap(50, 50); //assuming you want you image to be 50,50
    Bitmap originalImage = new Bitmap("myPngSource.png"); //original image to copy
    
    using (Graphics g = Graphics.FromImage(myImage))
    {
         g.DrawImage(originalImage, new Rectangle(0, 0, originalImage.Width, originalImage.Height));
    }
    
    MemoryStream ms = new MemoryStream();
    myImage.Save(ms, ImageFormat.Png);
    
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.StreamSource = ms;
    bi.EndInit();
    
    MyImageControl.Source = bi;
    

    Or something like that, this is untested, and I just ripped it out of a little utility app I made a while ago. I hope it helps... You just need to change the width of the final image and do a loop over the g.DrawImage call incrementing the second parameter by the width of the originalImage. (i.e. if you want 5 repeats, do a for loop 5 times)

    HTH --Mark