How to Use TextureBrush for painting an Image

how to locally refer to the image (it is set to always copy)

You can add the image to a resource file and then reference that Image from there within the code. (See link http://msdn.microsoft.com/en-us/library/7k989cfy%28v=vs.90%29.aspx)

How to get the image centered in the square, and how to keep the image stationary when the square moves?

This can be achieved using TranslateTransform with displayArea’s location (See link http://msdn.microsoft.com/en-us/library/13fy233f%28v=vs.110%29.aspx)

    TextureBrush imageBrush = new TextureBrush(runnerImage);

    imageBrush.WrapMode = WrapMode.Clamp;//causes the image to get smaller/larger if movement is tried

    Rectangle displayArea = new Rectangle(25, 25, 100, 200); //Random values I assigned

    Point xDisplayCenterRelative = new Point(displayArea.Width / 2, displayArea.Height / 2); //Find the relative center location of DisplayArea
    Point xImageCenterRelative = new Point(runnerImage.Width / 2, runnerImage.Height / 2); //Find the relative center location of Image
    Point xOffSetRelative = new Point(xDisplayCenterRelative.X - xImageCenterRelative.X, xDisplayCenterRelative.Y - xImageCenterRelative.Y); //Find the relative offset

    Point xAbsolutePixel = xOffSetRelative + new Size(displayArea.Location); //Find the absolute location

    imageBrush.TranslateTransform(xAbsolutePixel.X, xAbsolutePixel.Y);

    e.Graphics.FillRectangle(imageBrush, displayArea);
    e.Graphics.DrawRectangle(Pens.Black, displayArea); //I'm using PaintEventArgs graphics

Edit: I assumed that Image Size is always <= Square Size

Leave a Comment