WPF编游戏系列 之二 图标效果

       本篇将要实现图标的两个效果:1. 显示图标标签,2. 图标模糊效果。在上一篇中提到Image没有HTML <img>的Title属性(在MSDN中也没找到类似的属性),所以本篇将自行制作一个标签,它的功能是当鼠标移动到图标上方时会显示该图标的Tag说明,并且该图标模糊显示,如下图对比所示。

  原始状态                                                 效果状态

 t1           imagetitle

1. 在Home <Image>中加入MouseEnter和MouseLeave事件。

<Image Source="image/home.png" Width="110" Height="110" Tag="My Home" 
Canvas.Left="30" Canvas.Top="20" Cursor="Hand" MouseEnter="Image_BlurEffect_MouseEnter"
MouseLeave="Image_BlurEffect_MouseLeave"></Image>

2. 事件加好了,就要为添加内容了。先看Image_BlurEffect_MouseEnter事件:

private void Image_BlurEffect_MouseEnter(object sender, MouseEventArgs e)
{
  //将sender定义为Image对象
  Image image = sender as Image;
//创建模糊BlurEffect对象 BlurEffect newBlurEffect = new BlurEffect();
//设定模糊效果值Radius newBlurEffect.Radius = 5;
//为Image添加Blur效果 image.Effect = newBlurEffect;
//将Image Tag内容传给imageTitle Textblock imageTitle.Text = " " + image.Tag.ToString() + " ";
//将imageTitle的Border设置为可见 imageTitleBorder.Visibility = Visibility.Visible;
//调整imageTitleBorder的Canvas位置,使其在图标下方显示 Canvas.SetLeft(imageTitleBorder, Canvas.GetLeft(image) + image.Width / 2 - 15); Canvas.SetTop(imageTitleBorder, 125); }
private void Image_BlurEffect_MouseLeave(object sender, MouseEventArgs e)
{
  Image image = sender as Image;
  BlurEffect newBlurEffect = new BlurEffect();
  newBlurEffect.Radius = 0;
  image.Effect = newBlurEffect;
  imageTitleBorder.Visibility = Visibility.Collapsed;
}

       上一篇回复中,紫色永恒提到可以使用ToolTipService,首先感谢紫色永恒提供建议。经过测试使用ToolTip可以实现标签的功能(代码如下),而且也不用预设显示效果,但是没法通过Canvas设定其位置,大家可以都学习一下。

XAML:

<Image Source="image/home.png" Width="110" Height="110" 
Tag="My Home" Canvas.Left="30" Canvas.Top="20" MouseEnter="Image_BlurEffect_MouseEnter"
MouseLeave="Image_BlurEffect_MouseLeave" Cursor="Hand"> <Image.ToolTip> <TextBlock>My Home</TextBlock> </Image.ToolTip> </Image>

C#代码自然就简单多了:

private void Image_BlurEffect_MouseEnter(object sender, MouseEventArgs e)
{
   Image image = sender as Image;
   BlurEffect newBlurEffect = new BlurEffect();
   newBlurEffect.Radius = 5;
   image.Effect = newBlurEffect;
}

待续… …

posted @ 2009-12-09 11:49  Gnie  阅读(7077)  评论(15编辑  收藏  举报
Copyright © 2010 Gnie