一:注意事項:
1 .WPF項目的圖片資源,一定要做如下操作
- .將圖片生存操作設置為始終復制
如果不進行如下設置,本地的圖片不會在Image控件中顯示
二:使用的技術:
- 使用了Thread線程:用來循環更換圖片
- 使用DoubleAnimation:用來實現圖片的淡入和淡出
- 使用DispatcherFrame: 實現線程等待
三:核心代碼
/// <summary>
/// 設置延遲方法
/// </summary>
/// <param name="mm"></param>
public void Delay(int mm)
{
DateTime current = DateTime.Now;
while (current.AddMilliseconds(mm) > DateTime.Now)
{
DispatcherHelper.DoEvents();
}
return;
}
/// <summary>
/// Image的動畫效果
/// </summary>
public void SetImage()
{
DoubleAnimation daV2 = new DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(1)));
DoubleAnimation daV = new DoubleAnimation(1, 1, new Duration(TimeSpan.FromSeconds(1)));
Image1.BeginAnimation(UIElement.OpacityProperty, daV2);
Delay(500);
Image1.Source = new BitmapImage(new Uri("/Images/" + i + ".png", UriKind.Relative));
Image1.BeginAnimation(UIElement.OpacityProperty, daV);
Delay(500);
}
/// <summary>
/// 線程
/// </summary>
public void Start()
{
while (true)
{
if (flag)
{
int num = random.Next(1, 6);
if (i == num)
{
if (num == 5)
{
num = 1;
}
else
{
num += 1;
}
}
i = num;
ChangeImage change = new ChangeImage(SetImage);
//異步給Image1賦值
Image1.Dispatcher.BeginInvoke(change);
Delay(1000);
}
}
}
四:效果展示
五:源碼地址
源碼地址