日期:2014-05-18 浏览次数:21160 次
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
shapes.Add(new Rect() { Location = new Point(100, 100), Size = new Size(50, 30) });
shapes.Add(new Rect() { Location = new Point(220, 200), Size = new Size(20, 40) });
Random random = new Random();
timer.Tick += delegate
{
foreach (Shape shape in this.shapes)
{
shape.RotateAngle += random.Next(10);
this.Invalidate();
}
};
}
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Enabled = true, Interval = 100 };
List<Shape> shapes = new List<Shape>();
protected override void OnPaint(PaintEventArgs e)
{
foreach (Shape shape in shapes)
{
e.Graphics.TranslateTransform(shape.Location.X, shape.Location.Y);
shape.DrawTo(e.Graphics);
e.Graphics.ResetTransform();
}
}
public abstract class Shape
{
public abstract void DrawTo(Graphics g);
public float RotateAngle { get; set; }
public Point Location { get; set; }
}
public class Rect : Shape
{
public Size Size { get; set; }
public override void DrawTo(Graphics g)
{
PointF center = new PointF(Size.Width / 2.0f, Size.Height / 2.0f);
g.TranslateTransform(center.X, center.Y); //<--1
g.RotateTransform(RotateAngle); //<--2
g.TranslateTransform(-center.X, -center.Y); //<--3
g.FillRectangle(Brushes.PeachPuff, new Rectangle(Point.Empty, Size));
}
}