Project: MultiImage


How to generate images at runtime in WPF:
internal class ImageGenerator
	{
		public IEnumerable<ImageSource> GetImageList()
		{
			var imageList = new List<ImageSource>();
			const int Size = 50;

			var random = new Random();

			Func<int> nextCoordinate = () => random.Next(Size);
			Func<int> nextColor = () => random.Next(255);

			for (var i = 0; i < 10; i++)
			{
				var bitmap = CreateImage(Size, nextColor, nextCoordinate);
				var bitmapImage = GetBitmapSource(bitmap);

				imageList.Add(bitmapImage);
			}

			return imageList;
		}

		private BitmapSource GetBitmapSource(Bitmap image)
		{
			var bitmap = image;
			var bitmapSource = 
				Imaging
					.CreateBitmapSourceFromHBitmap(
						bitmap.GetHbitmap(),
						IntPtr.Zero,
						Int32Rect.Empty,
						System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
			
			return bitmapSource;
		}

		private Bitmap CreateImage(int size, Func<int> nextColor, Func<int> nextCoordinate)
		{
			var bitmap = new Bitmap(size, size);

			using (var graphics = Graphics.FromImage(bitmap))
			{
				graphics.Clear(Color.White);
				graphics.SmoothingMode = SmoothingMode.AntiAlias;
				graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

				var pen = new Pen(Color.FromArgb(nextColor(), nextColor(), nextColor()));

				graphics.DrawLine(pen, nextCoordinate(), nextCoordinate(), nextCoordinate(), nextCoordinate());
			}

			return bitmap;
		}
}

And visualize it in a ListBox:
<ListBox x:Name="listBox">
	<ListBox.ItemsPanel>
		<ItemsPanelTemplate>
			<UniformGrid Columns="3"/>
		</ItemsPanelTemplate>
	</ListBox.ItemsPanel>
	<ListBox.ItemTemplate>
		<DataTemplate>
			<Border 
				BorderBrush="Black" 
				BorderThickness="1">
				<Image 
					Source="{Binding}"
					Width="50"
					Height="50"
					Stretch="UniformToFill"
				/>
			</Border>
		</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

Last edited Aug 10, 2011 at 10:22 PM by teoarch, version 2

Comments

No comments yet.