我试图弄清楚如何让一个新的图像淡入,同时让旧的图像淡出。我最初想使用两种双动画,一种是淡入的,另一种是淡出的,完成后会互相触发,但是这对我来说不管用,因为我需要一幅图像淡入,另一幅正在褪色,我不知道该怎么做。
我想做的是:
XAML:
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"
xmlns:local="clr-namespace:Animation"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid x:Name="gridTest">
<StackPanel x:Name="stkHeaderBar" Grid.Row="0"
Orientation="Horizontal" FlowDirection="RightToLeft">
<Button x:Name="btnChangeImg" Content="Change Image"
Click="btnChangeImage_Click"/>
<Image x:Name="img"></Image>
</StackPanel>
</Grid>
代码背后:
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.Windows.Threading;
namespace Animation
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnChangeImage_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation fadeIn = new DoubleAnimation
{
From = 0,
To = 1,
Duration = TimeSpan.FromSeconds(2)
};
DoubleAnimation fadeOut = new DoubleAnimation
{
From = 1,
Duration = TimeSpan.FromSeconds(2),
};
fadeOut.Completed += (o, e) =>
{
img.Source = new BitmapImage(new Uri(@"C:\images.jpg"));
img.BeginAnimation(OpacityProperty, fadeIn);
};
fadeIn.Completed += (o, e) =>
{
img.Source = new BitmapImage(new Uri(@"C:\images.jpg"));
img.BeginAnimation(OpacityProperty, fadeOut);
};
img.Source = new BitmapImage(new Uri(@"C:\images1.jpg"));
img.BeginAnimation(OpacityProperty, fadeIn);
}
}
}
发布于 2022-05-30 02:43:43
这太复杂了,只需将这两个图像放在网格中,这样它们就会重叠:
<Grid>
<Image x:Name="img1" Stretch="UniformToFill"></Image>
<Image x:Name="img2" Stretch="UniformToFill"></Image>
</Grid>
第一幅图像的不透明度可以一直保持在1.0,然后您只需将第二幅图像动画化,使第二幅图像在上面淡入:
private void btnChangeImage_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation fadeIn = new DoubleAnimation
{
From = 0,
To = 1,
Duration = TimeSpan.FromSeconds(2)
};
img1.Source = new BitmapImage(new Uri(@"C:\image1.jpg"));
img2.Source = new BitmapImage(new Uri(@"C:\image2.jpg"));
img2.BeginAnimation(OpacityProperty, fadeIn);
}
如果您想彻底,那么您可以使用您的fadeIn.Completed处理程序在动画完成时删除img1,但我通常不会担心,除非它是一个资源关键的应用程序。
https://stackoverflow.com/questions/72428458
复制相似问题