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>

我有这段代码可以循环滚动网格中的单个图像。
现在我有 2 张图片 1(红色)和 2(黄色)看起来像这样。在此处输入图像描述 它会循环滚动

4

2 回答 2

3

ImageSource如果您想遵循当前的方法,可以基于多个图像构建单个。我有 2 个 png(图像文件夹中的 Desert1.png 和 Desert2.png)并使用 DataBinding 将 ImageBrush ImageSource 设置为在后面的代码中定义的属性:

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

这是背后的代码示例(您可以随意重构/使用/滥用):

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; }
    }
}
于 2014-01-20T18:30:27.113 回答
3

我有图像滑块的代码。我使用 Windows 手机的用户控件创建请查看此视频 http://www.screencast.com/t/XnhHwQFY第一次您需要更改逻辑。

但是,我认为您也可以将相同的代码用于 WPF

ImageSlider.xaml - 创建用户控件

<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 ,只需构建一次

SliderImage.cs -- 添加新类

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;
        }
    }
}

然后执行此步骤

MainPage.xaml 添加在 xaml 页面顶部xmlns:local="clr-namespace:[YOUR_PROJECT_NAMESPACE]"

然后添加只需在 xaml 中添加以下内容

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

MainPage.xaml.cs 加载图像

            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();

注意:我使用 ImageSliderDemo 作为我的命名空间。如果您使用不同,请确保您在用户控件中也进行了更新。而且我发现它只是第一次显示相同的图像两次。您可以更改 ImageSlider.xaml.cs 文件中的逻辑

于 2014-01-27T11:50:30.227 回答