nimbudew
nimbudew

Reputation: 978

Tiling image in a Grid

How can I tile a single image (small size) multiple times in a Grid container so that it appears that the Grid is holding one single image instead of multiple images tiled together?

I've seen methods that create a single image by copying the smaller image multiple times by blitting, but that process is computationally expensive. I don't want to create a bigger image; I just want to use the same single image multiple times so that the process doesn't require CPU cycles.

How can this be done?

UPDATE: It seems there exists no easy way to do the above. So, as a workaround, how can I create a single larger image by tiling multiple smaller images together in WP8.1 RT?

Upvotes: 0

Views: 206

Answers (1)

ntohl
ntohl

Reputation: 2125

In this code I have instantiated only one bitmap image. Tho, I'm not sure, if it is memory conserving.

{
      int n = 5;
      Grid grid = new Grid();
      BitmapImage bitmapImage = new BitmapImage(new Uri("pack://application:,,,/StackOverflowTest;Component/1.jpg"));
      for (int i = 0; i < n; i++)
      {
          grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});
          grid.RowDefinitions.Add(new RowDefinition {Height= GridLength.Auto});
      }
      for (int i = 0; i < n; i++)
      {
          for (int j = 0; j < n; j++)
          {                
              Image image = new Image { Source = bitmapImage };
              Grid.SetRow(image, i);
              Grid.SetColumn(image, j);
              grid.Children.Add(image);
          }
      }
      containerOfGrid.Children.Add(grid);
}

EDIT:

I have checked, and it seems to me, in Immediate window, that the source image is not allocated multiple times.

((System.Windows.Controls.Image)((new System.Linq.SystemCore_EnumerableDebugView(((System.Windows.Controls.Panel)(grid)).Children)).Items[0]))._bitmapSource.GetHashCode()
37855919
((System.Windows.Controls.Image)((new System.Linq.SystemCore_EnumerableDebugView(((System.Windows.Controls.Panel)(grid)).Children)).Items[1]))._bitmapSource.GetHashCode()
37855919
((System.Windows.Controls.Image)((new System.Linq.SystemCore_EnumerableDebugView(((System.Windows.Controls.Panel)(grid)).Children)).Items[0])).GetHashCode()
19914648
((System.Windows.Controls.Image)((new System.Linq.SystemCore_EnumerableDebugView(((System.Windows.Controls.Panel)(grid)).Children)).Items[1])).GetHashCode()
3378500

Upvotes: 1

Related Questions