1
我有一个gif动画。当我在CompactFramework中工作时,我遵循this MSDN example。使用MSDN示例错误的使用gif动画进行矩形绘制
基本的想法是将帧添加到图像,并用下一帧重画rectangle
,创建动画。除了动画以正方形显示,而不是我的图像的全尺寸(240,320)之外,它工作得很好。
这是我的代码:
一类AnimateCtl.cs:
public class AnimateCtl : System.Windows.Forms.Control
{
Timer fTimer;
int frameWidth = 240;
int frameHeight = 320;
int loopCount = 0;
int loopCounter = 0;
int frameCount;
int currentFrame = 0;
Graphics graphics;
private Bitmap bitmap;
public Bitmap Bitmap
{
get
{
return bitmap;
}
set
{
bitmap = value;
}
}
private void Draw(int iframe)
{
//Calculate the left location of the drawing frame
int XLocation = iframe * frameWidth;
Rectangle rect = new Rectangle(XLocation, 0, frameWidth, frameHeight);
//Draw image
graphics.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel);
}
public AnimateCtl()
{
//Cache the Graphics object
graphics = this.CreateGraphics();
//Instantiate the Timer
fTimer = new System.Windows.Forms.Timer();
//Hook up to the Timer's Tick event
fTimer.Tick += new System.EventHandler(this.timer1_Tick);
}
/// <summary>
/// Start animation
/// </summary>
/// <param name="frWidth"></param>
/// <param name="DelayInterval"></param>
/// <param name="LoopCount"></param>
public void StartAnimation(int frWidth, int DelayInterval, int LoopCount)
{
frameWidth = frWidth;
//How many times to loop
loopCount = LoopCount;
//Reset loop counter
loopCounter = 0;
//Calculate the frameCount
frameCount = bitmap.Width/frameWidth;
frameHeight = bitmap.Height;
//Resize the control
//this.Size(frameWidth, frameHeight);
//Assign delay interval to the timer
fTimer.Interval = DelayInterval;
//Start the timer
fTimer.Enabled = true;
}
private void timer1_Tick(object sender, System.EventArgs e)
{
if (loopCount == -1) //loop continuously
{
this.DrawFrame();
}
else
{
if (loopCount == loopCounter) //stop the animation
fTimer.Enabled = false;
else
this.DrawFrame();
}
}
private void DrawFrame()
{
if (currentFrame < frameCount - 1)
{
//move to the next frame
currentFrame++;
}
else
{
//increment the loopCounter
loopCounter++;
currentFrame = 0;
}
Draw(currentFrame);
}
,并在我的Form1中:
public partial class Form1 : Form
{
AnimateCtl animCtl;
public Form1()
{
InitializeComponent();
//Instantiate control
animCtl = new AnimateCtl();
//Assign the Bitmap from the image file
animCtl.Bitmap = new Bitmap(@"\Program Files\Animacion\Animacion-Frames.jpg");
//Set the location
animCtl.Location = new Point(0, 0);
//Add to control to the Form
this.Controls.Add(animCtl);
animCtl.StartAnimation(240, 100, 3);
}
}
为什么它不绘制矩形在正确的尺寸? 感谢您的帮助!
我添加了你的代码,它会产生相同的结果。事实上,如果我在'e.Graphics.DrawImage'后面调试OnPaint,它会绘制显示正方形的矩形。但矩形的尺寸应该是240x320。我不明白为什么会发生这种情况。谢谢你的帮助! –
您是否在将控件添加到控件集合后更改了控件的大小(animCtl)? animCtl.Size =新大小(240; 320); – Wowa
这就是问题所在!我加了'this.Size = new Size(240,320);'现在工作正常。谢谢! –