namespace WPMind.WP7.Controls
{
public partial class BubbleControl : UserControl
{
public BubbleControl()
{
// 为初始化变量所必需
InitializeComponent();
}
//更新气泡的位置
public void UpdatePosition(Point currentTransform)
{
var top = Canvas.GetTop(this);
var left = Canvas.GetLeft(this);
Canvas.SetTop(this, top - 5.0d + (currentTransform.Y * 0.1d));
Canvas.SetLeft(this, left + (currentTransform.X * 0.1d));
}
//判断气泡是否超出Canvas
public bool IsOutOfBounds(double width, double height)
{
var left = Canvas.GetLeft(this);
var top = Canvas.GetTop(this);
if (left < -ActualWidth)
return true;
if (left > width + ActualWidth)
return true;
if (top < -ActualHeight)
return true;
return false;
}
}
} 在Demo页面中,我们首先生成25个位置随机、大小随机的气泡,然后开启定时器,溢出时间是50ms:
public MainPage()
{
InitializeComponent();
Loaded += OnLoaded;
timer.Tick += OnTimerTicker;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
CreateInitialBubbles();
timer.Start();
}
//生成初始的气泡
private void CreateInitialBubbles()
{
for (int i = 0; i < 25; i++)
{
var left = random.NextDouble() * ContentCanvas.ActualWidth;
var top = random.NextDouble() * ContentCanvas.ActualHeight;
var size = random.Next(10, 50);
CreateBubble(left, top, size);
}
}
private void CreateBubble(double left, double top, double size)
{
var bubblecontrol = new BubbleControl
{
Width = size,
Height = size
};
Canvas.SetLeft(bubblecontrol, left);
Canvas.SetTop(bubblecontrol, top);
ContentCanvas.Children.Add(bubblecontrol);
} 在定时器超时处理中,遍历所有气泡,更新其位置。然后判断它是否越界,如果越界就移除,并添加一个新的气泡进来。