<Canvas x:Name="container" Width="800" Height="600" Background="Silver"
MouseLeftButtonDown="container_MouseLeftButtonDown">
</Canvas>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Imaging;
using System.Windows.Shapes;
namespace WPFApplication
{
/// <summary>
/// chap02.xaml 的交互逻辑
/// </summary>
public partial class chap02 : Window
{
public chap02()
{
InitializeComponent();
DrawPentacle();
}
private void DrawPentacle()
{
pentacle = new Polygon();
pentacle.Stroke = System.Windows.Media.Brushes.DarkGray;
pentacle.StrokeThickness = 0.1;
pentacle.Fill = new SolidColorBrush(Colors.Red);
pentacle.Opacity = 0.4;
PointCollection pointCollection = new PointCollection();
pointCollection.Add(new Point(0,0));
pointCollection.Add(new Point(100,0));
pointCollection.Add(new Point(100,100));
pointCollection.Add(new Point(0,100));
pentacle.Points = pointCollection;
Canvas.SetLeft(pentacle, 0);
Canvas.SetTop(pentacle, 0);
container.Children.Add(pentacle);
CompositionTarget.Rendering += new EventHandler(TimeTick);
}
private void TimeTick(object sender, EventArgs e)
{
double pentacleX = Canvas.GetLeft(pentacle);
double pentacleY = Canvas.GetTop(pentacle);
Canvas.SetLeft(pentacle, (moveTo.X > pentacleX) ? (pentacleX + speed) : (pentacleX - speed));
Canvas.SetTop(pentacle, (moveTo.Y > pentacleY) ? (pentacleY + speed) : (pentacleY - speed));
}
private void container_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
moveTo = e.GetPosition(container);
}
private Polygon pentacle;
private int speed = 1;
private Point moveTo;
}
}