Csharp/C Sharp/2D Graphics/Animation — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:42, 26 мая 2010
Содержание
Animate Demo
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace Animate_c
{
public class AnimateDemo : System.Windows.Forms.Form
{
private System.Windows.Forms.Button cmdGo;
/// <summary>
/// Required designer variable.
/// </summary>
///
Bitmap RotatingBlocks;
Point DrawHere;
Rectangle InvalidRect;
bool InProcess = false;
private System.Windows.Forms.Button cmdStop;
private System.ruponentModel.Container components = null;
public AnimateDemo()
{
InitializeComponent();
RotatingBlocks = new Bitmap("blocks.gif");
DrawHere = new Point(10, 10);
InvalidRect = new Rectangle(DrawHere, RotatingBlocks.Size);
this.SetStyle(ControlStyles.AllPaintingInWmPaint,true);
this.SetStyle(ControlStyles.DoubleBuffer,true);
cmdStop.Enabled = false;
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
RotatingBlocks.Dispose();
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdGo = new System.Windows.Forms.Button();
this.cmdStop = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// cmdGo
//
this.cmdGo.Location = new System.Drawing.Point(160, 120);
this.cmdGo.Name = "cmdGo";
this.cmdGo.Size = new System.Drawing.Size(64, 32);
this.cmdGo.TabIndex = 0;
this.cmdGo.Text = "Animate";
this.cmdGo.Click += new System.EventHandler(this.cmdGo_Click);
//
// cmdStop
//
this.cmdStop.Location = new System.Drawing.Point(240, 120);
this.cmdStop.Name = "cmdStop";
this.cmdStop.Size = new System.Drawing.Size(56, 32);
this.cmdStop.TabIndex = 1;
this.cmdStop.Text = "Stop";
this.cmdStop.Click += new System.EventHandler(this.cmdStop_Click);
//
// AnimateDemo
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(312, 157);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.cmdStop,
this.cmdGo});
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AnimateDemo";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "AnimateDemo";
this.Load += new System.EventHandler(this.AnimateDemo_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new AnimateDemo());
}
private void AnimateDemo_Load(object sender, System.EventArgs e)
{
}
private void OnFrameChanged(object o, EventArgs e)
{
//Force a call to the Paint event handler.
this.Invalidate(InvalidRect);
}
protected override void OnPaint(PaintEventArgs e)
{
if ( !InProcess )
return;
//Get the next block ready to display.
ImageAnimator.UpdateFrames(RotatingBlocks);
//Draw the next frame in the RotatingBlocks animation.
e.Graphics.DrawImage(RotatingBlocks, DrawHere);
}
private void cmdGo_Click(object sender, System.EventArgs e)
{
if (!InProcess)
{
if ( ImageAnimator.CanAnimate(RotatingBlocks) )
{
//Begin the animation only once.
ImageAnimator.Animate(RotatingBlocks,
new EventHandler(this.OnFrameChanged));
InProcess = true;
cmdGo.Enabled = false;
cmdStop.Enabled = true;
}
}
}
private void cmdStop_Click(object sender, System.EventArgs e)
{
ImageAnimator.StopAnimate(RotatingBlocks,
new EventHandler(this.OnFrameChanged));
InProcess = false;
cmdGo.Enabled = true;
cmdStop.Enabled = false;
}
}
}
<A href="http://www.nfex.ru/Code/CSharpDownload/Animate-c.zip">Animate-c.zip( 6 k)</a>
Animate Image
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Animate_c
{
public class animateImage : Form
{
//Create a Bitmpap Object.
Bitmap animatedImage = new Bitmap("1.gif");
bool currentlyAnimating = false;
//This method begins the animation.
public void AnimateImage()
{
if (!currentlyAnimating)
{
//Begin the animation only once.
ImageAnimator.Animate(animatedImage, new EventHandler(this.OnFrameChanged));
currentlyAnimating = true;
}
}
private void OnFrameChanged(object o, EventArgs e)
{
//Force a call to the Paint event handler.
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
//Begin the animation.
AnimateImage();
//Get the next frame ready for rendering.
ImageAnimator.UpdateFrames();
//Draw the next frame in the animation.
e.Graphics.DrawImage(this.animatedImage, new Point(0, 0));
}
public static void Main()
{
Application.Run(new animateImage());
}
}
}
Animate Image with ImageAnimator
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
private Bitmap bmp;
public Form1()
{
}
private void Form1_Load(object sender, EventArgs e)
{
bmp = new Bitmap("arrow.gif");
ImageAnimator.Animate(bmp, new EventHandler(this.OnFrameChanged));
}
private void OnFrameChanged(object o, EventArgs e)
{
this.Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
ImageAnimator.UpdateFrames();
e.Graphics.DrawImage(this.bmp, new Point(0, 0));
}
}
Animates a circle
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
public class AnimateFace : Form {
private int x = 10, y = 10;
private int width = 200, height = 200;
private Button suspend = new Button();
private Button resume = new Button();
private Button abort = new Button();
private Thread t;
public AnimateFace() {
BackColor = Color.White;
abort.Text = "Abort";
suspend.Text = "Suspend";
resume.Text = "Resume";
Controls.Add(suspend);
Controls.Add(resume);
Controls.Add(abort);
int w = 20;
suspend.Location = new Point(w, 240);
resume.Location = new Point(w += 10 + suspend.Width, 240);
abort.Location = new Point(w += 10 + resume.Width, 240);
abort.Click += new EventHandler(Abort_Click);
suspend.Click += new EventHandler(Suspend_Click);
resume.Click += new EventHandler(Resume_Click);
t = new Thread(new ThreadStart(Run));
t.Start();
}
protected void Abort_Click(object sender, EventArgs e) {
t.Abort();
}
protected void Suspend_Click(object sender, EventArgs e) {
t.Suspend();
}
protected void Resume_Click(object sender, EventArgs e) {
t.Resume();
}
protected override void OnPaint( PaintEventArgs e ) {
Graphics g = e.Graphics;
Pen green = new Pen(Color.Green, 3);
Brush red = new SolidBrush(Color.Red);
g.DrawEllipse(green, x, y, width, height);
base.OnPaint(e);
}
public void Run() {
int dx=9, dy=9;
while (true) {
for (int i = 0; i < 30; i++) {
x += dx;
y += dy;
width -= dx;
height -= dy;
Invalidate();
Thread.Sleep(30);
}
dx = -dx; dy = -dy;
}
}
public static void Main( ) {
Application.Run(new AnimateFace());
}
}
Animates an image
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
public class AnimateImage : Form {
private int width = 10;
private int height = 10;
Image pic = Image.FromFile("winter.jpg");
private Button abort = new Button();
Thread t;
public AnimateImage() {
abort.Text = "Abort";
abort.Location = new Point(50, 230);
abort.Click += new EventHandler(Abort_Click);
Controls.Add(abort);
SetStyle(ControlStyles.DoubleBuffer
| ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint, true);
t = new Thread(new ThreadStart(Run));
t.Start();
}
protected void Abort_Click(object sender, EventArgs e) {
t.Abort();
}
protected override void OnPaint( PaintEventArgs e ) {
Graphics g = e.Graphics;
g.DrawRectangle(Pens.Black, 8, 8, width+3, height+3);
g.DrawImage(pic, 10, 10, width, height);
base.OnPaint(e);
}
public void Run() {
int dx=5, dy=5;
while (true) {
for(int i = 0; i < 500; i++) {
width += dx;
height += dy;
Invalidate();
Thread.Sleep(30);
}
dx = -dx; dy = -dy;
}
}
public static void Main( ) {
Application.Run(new AnimateImage());
}
}
Animation and double buffer
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
private bool isShrinking = false;
private int extraSize = 0;
private System.Windows.Forms.Timer tmrRefresh;
private System.Windows.Forms.CheckBox chkDoubleBuffer;
public Form1() {
InitializeComponent();
tmrRefresh.Start();
}
private void tmrRefresh_Tick(object sender, System.EventArgs e)
{
if (isShrinking)
extraSize--;
else
extraSize++;
if (extraSize > 500)
isShrinking = true;
else if (extraSize < 1)
isShrinking = false;
this.Invalidate();
}
private void DoubleBuffering_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
this.DoubleBuffered = chkDoubleBuffer.Checked;
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Pen drawingPen = new Pen(Color.Black, 10);
g.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0),
this.ClientSize));
g.DrawRectangle(drawingPen, 50, 50, 50 + extraSize, 50 + extraSize);
}
private void InitializeComponent()
{
this.tmrRefresh = new System.Windows.Forms.Timer(new System.ruponentModel.Container());
this.chkDoubleBuffer = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// tmrRefresh
//
this.tmrRefresh.Interval = 1;
this.tmrRefresh.Tick += new System.EventHandler(this.tmrRefresh_Tick);
//
// chkDoubleBuffer
//
this.chkDoubleBuffer.BackColor = System.Drawing.Color.White;
this.chkDoubleBuffer.Location = new System.Drawing.Point(12, 12);
this.chkDoubleBuffer.Name = "chkDoubleBuffer";
this.chkDoubleBuffer.Size = new System.Drawing.Size(336, 16);
this.chkDoubleBuffer.TabIndex = 2;
this.chkDoubleBuffer.Text = "Use Double Buffering";
this.chkDoubleBuffer.UseVisualStyleBackColor = false;
//
// DoubleBuffering
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(422, 373);
this.Controls.Add(this.chkDoubleBuffer);
this.Name = "DoubleBuffering";
this.Text = "Form1";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.DoubleBuffering_Paint);
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
Button click action to move a ball
using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonToMove : Form {
private int x = 50, y = 50;
private Button move = new Button();
public ButtonToMove() {
move.Text = "Move";
move.Location = new Point(5,5);
Controls.Add(move);
move.Click += new EventHandler(Move_Click);
}
protected void Move_Click(object sender, EventArgs e) {
x += 9;
y += 9;
Invalidate();
}
protected override void OnPaint( PaintEventArgs e ) {
Graphics g = e.Graphics;
Brush red = new SolidBrush(Color.Red);
g.FillEllipse(red ,x ,y, 20 ,20);
base.OnPaint(e);
}
public static void Main( ) {
Application.Run(new ButtonToMove());
}
}
No Flicker (Flicker Free) Animation
/*
Code revised from chapter 9
GDI+ Custom Controls with Visual C# 2005
By Iulian Serban, Dragos Brezoi, Tiberiu Radu, Adam Ward
Language English
Paperback 272 pages [191mm x 235mm]
Release date July 2006
ISBN 1904811604
Sample chapter
http://www.packtpub.ru/files/1604_CustomControls_SampleChapter.pdf
For More info on GDI+ Custom Control with Microsoft Visual C# book
visit website www.packtpub.ru
*/
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FlickerFree
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void tbInterval_Scroll(object sender, EventArgs e)
{
scrollingText.ScrollTimeInterval = tbInterval.Value;
}
private void tbAmount_Scroll(object sender, EventArgs e)
{
scrollingText.ScrollPixelAmount = tbAmount.Value;
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.scrollingText = new FlickerFree.ScrollingText();
this.grpTrackerBars = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.tbAmount = new System.Windows.Forms.TrackBar();
this.tbInterval = new System.Windows.Forms.TrackBar();
this.grpTrackerBars.SuspendLayout();
((System.ruponentModel.ISupportInitialize)(this.tbAmount)).BeginInit();
((System.ruponentModel.ISupportInitialize)(this.tbInterval)).BeginInit();
this.SuspendLayout();
//
// scrollingText
//
this.scrollingText.BackColor = System.Drawing.Color.LightGray;
this.scrollingText.Font = new System.Drawing.Font("Verdana", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.scrollingText.ForeColor = System.Drawing.Color.Navy;
this.scrollingText.Location = new System.Drawing.Point(38, 29);
this.scrollingText.Margin = new System.Windows.Forms.Padding(12, 10, 12, 10);
this.scrollingText.Name = "scrollingText";
this.scrollingText.ScrollPixelAmount = 10;
this.scrollingText.ScrollTimeInterval = 100;
this.scrollingText.Size = new System.Drawing.Size(300, 80);
this.scrollingText.TabIndex = 0;
this.scrollingText.Text = "Scrolling Text that Scrolls";
//
// grpTrackerBars
//
this.grpTrackerBars.Controls.Add(this.tbInterval);
this.grpTrackerBars.Controls.Add(this.tbAmount);
this.grpTrackerBars.Controls.Add(this.label2);
this.grpTrackerBars.Controls.Add(this.label1);
this.grpTrackerBars.Location = new System.Drawing.Point(38, 132);
this.grpTrackerBars.Name = "grpTrackerBars";
this.grpTrackerBars.Size = new System.Drawing.Size(322, 183);
this.grpTrackerBars.TabIndex = 1;
this.grpTrackerBars.TabStop = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 37);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Scroll Amount";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(10, 134);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(71, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Scroll Interval";
//
// tbAmount
//
this.tbAmount.Location = new System.Drawing.Point(101, 19);
this.tbAmount.Maximum = 20;
this.tbAmount.Name = "tbAmount";
this.tbAmount.Size = new System.Drawing.Size(200, 45);
this.tbAmount.TabIndex = 2;
this.tbAmount.Value = 1;
this.tbAmount.Scroll += new System.EventHandler(this.tbAmount_Scroll);
//
// tbInterval
//
this.tbInterval.Location = new System.Drawing.Point(101, 123);
this.tbInterval.Maximum = 500;
this.tbInterval.Minimum = 10;
this.tbInterval.Name = "tbInterval";
this.tbInterval.Size = new System.Drawing.Size(200, 45);
this.tbInterval.TabIndex = 3;
this.tbInterval.TickFrequency = 10;
this.tbInterval.Value = 100;
this.tbInterval.Scroll += new System.EventHandler(this.tbInterval_Scroll);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(456, 332);
this.Controls.Add(this.grpTrackerBars);
this.Controls.Add(this.scrollingText);
this.Name = "Form1";
this.Text = "Form1";
this.grpTrackerBars.ResumeLayout(false);
this.grpTrackerBars.PerformLayout();
((System.ruponentModel.ISupportInitialize)(this.tbAmount)).EndInit();
((System.ruponentModel.ISupportInitialize)(this.tbInterval)).EndInit();
this.ResumeLayout(false);
}
#endregion
private ScrollingText scrollingText;
private System.Windows.Forms.GroupBox grpTrackerBars;
private System.Windows.Forms.TrackBar tbInterval;
private System.Windows.Forms.TrackBar tbAmount;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public partial class ScrollingText : UserControl
{
private string text;
private int scrollAmount = 10;
private int position = 10;
public ScrollingText()
{
InitializeComponent();
}
private void ScrollingText_Load(object sender, EventArgs e)
{
this.ResizeRedraw = true;
if (!this.DesignMode)
{
scrollTimer.Enabled = true;
}
}
private void scrollTimer_Tick(object sender, EventArgs e)
{
position += scrollAmount;
this.Invalidate();
}
[Browsable(true),DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text
{
get
{
return text;
}
set
{
text = value;
this.Invalidate();
}
}
public int ScrollTimeInterval
{
get
{
return scrollTimer.Interval;
}
set
{
scrollTimer.Interval = value;
}
}
public int ScrollPixelAmount
{
get
{
return scrollAmount;
}
set
{
scrollAmount = value;
}
}
private void ScrollingText_Paint(object sender, PaintEventArgs e)
{
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// to avoid a design-time error we need to add the following line
if (e.ClipRectangle.Width == 0)
{
return;
}
base.OnPaint(e);
if (position > this.Width)
{
// Reset the text to scroll back onto the control.
position = -(int)e.Graphics.MeasureString(text, this.Font).Width;
}
// Create the drawing area in memory.
// Double buffering is used to prevent flicker.
Bitmap bufl = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height);
Graphics g = Graphics.FromImage(bufl);
g.FillRectangle(new SolidBrush(this.BackColor), e.ClipRectangle);
g.DrawString(text, this.Font, new SolidBrush(this.ForeColor), position, 0);
// Render the finished image on the form.
e.Graphics.DrawImageUnscaled(bufl, 0, 0);
g.Dispose();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ruponents = new System.ruponentModel.Container();
this.scrollTimer = new System.Windows.Forms.Timer(this.ruponents);
this.SuspendLayout();
//
// scrollTimer
//
this.scrollTimer.Tick += new System.EventHandler(this.scrollTimer_Tick);
//
// ScrollingText
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "ScrollingText";
this.Size = new System.Drawing.Size(400, 100);
this.Load += new System.EventHandler(this.ScrollingText_Load);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.ScrollingText_Paint);
this.ResumeLayout(false);
}
#endregion
internal System.Windows.Forms.Timer scrollTimer;
}
}
Object collision
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class Form1 : System.Windows.Forms.Form {
private int dx = 4;
private System.Windows.Forms.PictureBox picTarget;
private System.Windows.Forms.PictureBox picBall;
private System.Windows.Forms.Timer timer1;
public Form1() {
InitializeComponent();
}
private void InitializeComponent() {
this.picTarget = new System.Windows.Forms.PictureBox();
this.picBall = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(new System.ruponentModel.Container());
this.SuspendLayout();
this.picTarget.BackColor = Color.Red;
this.picTarget.Location = new System.Drawing.Point(160, 240);
this.picTarget.Name = "picTarget";
this.picTarget.Size = new System.Drawing.Size(56, 56);
this.picTarget.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picTarget.TabIndex = 0;
this.picTarget.TabStop = false;
this.picBall.Image = new Bitmap("winter.jpg");
this.picBall.Location = new System.Drawing.Point(24, 136);
this.picBall.Name = "picBall";
this.picBall.Size = new System.Drawing.Size(32, 32);
this.picBall.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picBall.TabIndex = 1;
this.picBall.TabStop = false;
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(392, 341);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.picBall,
this.picTarget});
this.Name = "Form1";
this.Text = "Crasher";
this.ResumeLayout(false);
}
[STAThread]
static void Main() {
Application.Run(new Form1());
}
private void timer1_Tick(object sender, System.EventArgs e) {
int newX, newY;
newX = picBall.Location.X + dx;
newY = picBall.Location.Y + dx;
if (newX > this.Width - picBall.Width){
dx = - dx;
}
if (newX < 0){
dx = - dx;
}
if (picBall.Bounds.IntersectsWith(picTarget.Bounds)){
this.BackColor = Color.Black;
} else {
this.BackColor = Color.White;
}
picBall.Location = new Point(newX, newY);
}
}
Timer based animation
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class Form1 : System.Windows.Forms.Form{
private System.ruponentModel.IContainer components;
public Form1(){
InitializeComponent();
}
#region Windows Form Designer generated code
private void InitializeComponent(){
this.ruponents = new System.ruponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.ruponents);
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(292, 260);
this.Name = "Form1";
this.Text = "LinearGradientBrush Demo";
this.Load += new System.EventHandler(this.Form1_Load);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
#endregion
static void Main(){
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e) {
this.BackColor = Color.FromArgb(255, 0, 0, 255);
}
private System.Windows.Forms.Timer timer1;
private float angle = 0;
private LinearGradientBrush GetBrush()
{
return new LinearGradientBrush(
new Rectangle( 20, 20, 200, 100),
Color.Orange,
Color.Yellow,
0.0F,
true);
}
private void Rotate( Graphics graphics, LinearGradientBrush brush )
{
brush.RotateTransform(angle);
brush.SetBlendTriangularShape(.5F);
graphics.FillRectangle(brush, brush.Rectangle);
}
private void Rotate(Graphics graphics)
{
angle += 5 % 360;
Rotate(graphics, GetBrush());
}
private void timer1_Tick(object sender, System.EventArgs e)
{
Rotate(CreateGraphics());
}
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Rotate(e.Graphics);
}
}
Uses a thread to Animate a ball
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
public class AnimateBall : Form {
private int x, y;
private Button suspend = new Button();
private Button resume = new Button();
private Button abort = new Button();
Thread t;
public AnimateBall() {
BackColor = Color.White;
abort.Text = "Abort";
suspend.Text = "Suspend";
resume.Text = "Resume";
int w = 20;
suspend.Location = new Point(w, 200);
resume.Location = new Point(w += 10 + suspend.Width, 200);
abort.Location = new Point(w += 10 + resume.Width, 200);
abort.Click += new EventHandler(Abort_Click);
suspend.Click += new EventHandler(Suspend_Click);
resume.Click += new EventHandler(Resume_Click);
Controls.Add(suspend);
Controls.Add(resume);
Controls.Add(abort);
t = new Thread(new ThreadStart(Run));
t.Start();
}
protected void Abort_Click(object sender, EventArgs e) {
t.Abort();
}
protected void Suspend_Click(object sender, EventArgs e) {
t.Suspend();
}
protected void Resume_Click(object sender, EventArgs e) {
t.Resume();
}
protected override void OnPaint( PaintEventArgs e ) {
Graphics g = e.Graphics;
g.FillEllipse(Brushes.Red, 100 ,y, 4 ,4);
base.OnPaint(e);
}
public void Run() {
int dx=2, dy=2;
y = 1;
while (true) {
for(int i=0; i<140; i++) {
y+=dy;
Invalidate();
Thread.Sleep(10);
}
dx = -dx; dy = -dy;
}
}
public static void Main( ) {
Application.Run(new AnimateBall());
}
}