3
<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="Images\Desert.jpg"
            Stretch="UniformToFill" TileMode="Tile"
            ViewportUnits="Absolute" Viewport="0,0,1024,768"/>
    </Grid.Background>
    <Grid.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <RectAnimation Storyboard.TargetProperty="Background.Viewport"
                           To="-1024,0,1024,768" Duration="0:0:10" 
                           RepeatBehavior="Forever"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Grid.Triggers>
</Grid>

I have this code that scroll a single image in a grid with looping.
Now I have 2 images 1(red) and 2(yellow) am looking something like this. enter image description here and it will scroll in loop

madan
  • 773
  • 13
  • 38

2 Answers2

3

You can build a single ImageSource based on multiple images if you wanted to follow your current approach. I have 2 png's (Desert1.png and Desert2.png in an Images folder) and use DataBinding to set the ImageBrush ImageSource to a property defined on the code behind:

<!- Your original xaml ... only difference is the binding -->
<ImageBrush ImageSource="{Binding CombinedImage}"
            Stretch="None" TileMode="Tile"
            ViewportUnits="Absolute" Viewport="0,0,1024,768"/>

Here's a sample of the code behind (feel free to refactor / use / abuse as you see fit):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xaml;

namespace WpfApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var uriSource1 = new Uri(@"pack://application:,,,/Images/Desert1.png", UriKind.Absolute);
            BitmapImage bitmapImage1 = new BitmapImage(uriSource1);

            var uriSource2 = new Uri(@"pack://application:,,,/Images/Desert2.png", UriKind.Absolute);
            BitmapImage bitmapImage2 = new BitmapImage(uriSource2);

            this.DataContext = this;

            List<BitmapImage> images = new List<BitmapImage>() { bitmapImage1, bitmapImage2 };
            CombinedImage = GetCombinedImage(images);
        }

        private static RenderTargetBitmap GetCombinedImage(IEnumerable<BitmapImage> images )
        {
            // Get total width of all images
            int totalWidthOfAllImages = images.Sum(p => (int)p.Width);
            // Get max height of all images
            int maxHeightOfAllImages = images.Max(p => (int)p.Height);

            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                double left = 0;
                foreach (BitmapImage image in images)
                {
                    drawingContext.DrawImage(image, new Rect(left, 0, image.Width, image.Height));
                    left += image.Width;
                }
            }

            RenderTargetBitmap bmp = new RenderTargetBitmap(totalWidthOfAllImages, maxHeightOfAllImages, 96, 96, PixelFormats.Default);
            bmp.Render(drawingVisual);
            return bmp;
        }

        public ImageSource CombinedImage { get; private set; }
    }
}
KornMuffin
  • 2,887
  • 3
  • 32
  • 48
  • Thank you @KornMuffin this code worked but if i take 2 images both are showing 50% – madan Jan 24 '14 at 13:50
  • You're welcome @madan. What size images are you using? Let me know and I'll try it out. Is the XAML container too small to fit the combined image? – KornMuffin Jan 24 '14 at 14:05
  • My images were small (259x194 and 277x182). I tried with 2 larger 960x631 and see what you mean. It probably is due to the size of the Viewport. You may need to make that dynamic (via Binding) so it'll size to the combined image. – KornMuffin Jan 26 '14 at 18:10
3

I have code for image slider. I created using user control for windows phone Please check with this video http://www.screencast.com/t/XnhHwQFY For first time you need to change logic.

But, I think same code you can use for WPF also

ImageSlider.xaml - Create user control

<UserControl x:Class="ImageSliderDemo.ImageSlider"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480">

    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
        <Canvas Height="220" x:Name="imageSliderCanvas" Width="451">
            <Image x:Name="imageViewOne"
                        Canvas.Left="0"
                        Canvas.Top="0"
                        Height="220" Width="440" Canvas.ZIndex="9">
                <Image.RenderTransform>
                    <TranslateTransform />
                </Image.RenderTransform>
            </Image>
            <Image x:Name="imageViewTwo"
                        Canvas.Left="0"
                        Height="220" Width="440" Canvas.ZIndex="10">
                <Image.RenderTransform>
                    <TranslateTransform />
                </Image.RenderTransform>
            </Image>
        </Canvas>
        <StackPanel x:Name="PART_Host" />
    </Grid>
</UserControl>

ImageSlider.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Markup;

namespace ImageSliderDemo
{
    public partial class ImageSlider : UserControl
    {
        private const int LOWER_ZINDEX = 9, UPPER_ZINDEX = 11, POSITION_FROM480 = 480, POSITION_TO0 = 0;
        private int nextImage = 1;

        #region "Image Slider Properies"
        #region "Property - Length Readonly"
        public static readonly DependencyProperty LengthProperty = DependencyProperty.Register("Length", typeof(int), typeof(ImageSlider), new PropertyMetadata(0));
        public int Length
        {
            get { return (int)GetValue(LengthProperty); }
            private set { SetValue(LengthProperty, value); }
        }
        #endregion

        #region "Property - Begin Delay Readonly"
        public static readonly DependencyProperty BeginDelayProperty = DependencyProperty.Register("BeginDelay", typeof(double), typeof(ImageSlider), new PropertyMetadata(5000.00));
        public double BeginDelay
        {
            get { return (double)GetValue(BeginDelayProperty); }
            set { SetValue(BeginDelayProperty, value); }
        }
        #endregion

        #region "Property - Animation Duration Readonly"
        public static readonly DependencyProperty AnimationDurationProperty = DependencyProperty.Register("AnimationDuration", typeof(double), typeof(ImageSlider), new PropertyMetadata(900.00));
        public double AnimationDuration
        {
            get { return (double)GetValue(AnimationDurationProperty); }
            set { SetValue(AnimationDurationProperty, value); }
        }
        #endregion

        #region "Property - Images"
        public static readonly DependencyProperty ImagesProperty = DependencyProperty.Register("Images", typeof(List<SliderImage>), typeof(ImageSlider), new PropertyMetadata(null));
        public List<SliderImage> Images
        {
            get { return (List<SliderImage>)GetValue(ImagesProperty); }
            set { SetValue(ImagesProperty, value); }
        }
        #endregion
        #endregion

        public ImageSlider()
        {
            InitializeComponent();
        }

        /// <summary>
        /// This Start method used begin the animation
        /// </summary>
        public void Start()
        {
            if (this.Images != null)
            {
                this.Length = this.Images.Count;
                hidePrevious(imageViewOne);
                showNext(imageViewTwo);
            }
            else
            {
                MessageBox.Show("Please add atleast two images");
            }
        }


        #region "Animation methods"
        private void showNext(Image imageView)
        {
            TranslateTransform trans = imageView.RenderTransform as TranslateTransform;
            DoubleAnimation animation = new DoubleAnimation();
            animation.To = POSITION_TO0;
            animation.Duration = TimeSpan.FromMilliseconds(this.AnimationDuration);
            animation.From = POSITION_FROM480;
            animation.BeginTime = TimeSpan.FromMilliseconds(this.BeginDelay);
            Storyboard.SetTarget(animation, trans);
            Storyboard.SetTargetProperty(animation, new
            PropertyPath(TranslateTransform.XProperty));
            // Create storyboard, add animation, and fire it up!
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(animation);
            storyboard.Begin();
            Canvas.SetZIndex(imageView, UPPER_ZINDEX);
            imageView.Visibility = Visibility.Visible;
            if (nextImage > this.Length)
            {
                nextImage = 1;
            }

            BitmapImage nextBitmapImage = new BitmapImage(new Uri(this.Images[nextImage-1].Path, UriKind.Relative));
            imageView.Source = nextBitmapImage;
            nextImage++;
        }

        private void hidePrevious(Image imageView)
        {
            TranslateTransform trans = imageView.RenderTransform as TranslateTransform;
            DoubleAnimation animation = new DoubleAnimation();
            animation.To = - POSITION_FROM480;
            animation.Duration = TimeSpan.FromMilliseconds(this.AnimationDuration);
            animation.From = POSITION_TO0;
            animation.BeginTime = TimeSpan.FromMilliseconds(this.BeginDelay);
            Storyboard.SetTarget(animation, trans);
            Storyboard.SetTargetProperty(animation, new
            PropertyPath(TranslateTransform.XProperty));
            // Create storyboard, add animation, and fire it up!
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(animation);
            storyboard.Begin();
            animation.Completed += hideAnimation_Completed;
        }

        private void hideAnimation_Completed(object sender, EventArgs e)
        {
            if (Canvas.GetZIndex(imageViewOne) > Canvas.GetZIndex(imageViewTwo))
            {
                Canvas.SetZIndex(imageViewOne, LOWER_ZINDEX);
                hidePrevious(imageViewOne);
                showNext(imageViewTwo);
            }
            else
            {
                Canvas.SetZIndex(imageViewTwo, LOWER_ZINDEX);
                hidePrevious(imageViewTwo);
                showNext(imageViewOne);
            }
        }
        #endregion
    }

}

Ctrl + B , Just build once

SliderImage.cs -- Add new class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ImageSliderDemo
{
    public class SliderImage
    {
        public string Name { get; set; }
        public string Path { get; set; }

        public SliderImage(string name, string path)
        {
            this.Name = name;
            this.Path = path;
        }
    }
}

then do this steps

MainPage.xaml add at top of xaml page xmlns:local="clr-namespace:[YOUR_PROJECT_NAMESPACE]"

then add just add this below in xaml

<local:ImageSlider x:Name="imageSlider"/>

MainPage.xaml.cs load images

            List<SliderImage> images = new List<SliderImage>();
            images.Add(new SliderImage("One", "Images/1.png"));
            images.Add(new SliderImage("Two", "Images/2.png"));
            images.Add(new SliderImage("Three", "Images/3.png"));
            images.Add(new SliderImage("Four", "Images/4.png"));
            imageSlider.Images = images;
            imageSlider.Start();

Note : I used ImageSliderDemo as my namespace. If your using different please make sure you updated in user control as well. And I found only first time it is show same image twice. you can change the logic in ImageSlider.xaml.cs file

Naga Harish M
  • 2,779
  • 2
  • 31
  • 45