ASP.NET教程:用Timer控件在窗体中实现动画效果
来源:学生作业帮助网 编辑:作业帮 时间:2024/05/15 10:28:01 ASP.NET
C#用Timer控件可以在窗体中实现动画效果,动画非常顺畅。下面代码是实现字体大小渐变动画的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class UseTimer : Form
{
private const float maxSize = 70F;
private const float step = 1F;
private float current = 10F;
private const string text = "这是我的作品,谢谢观赏!";
public UseTimer()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint,true);
SetStyle(ControlStyles.OptimizedDoubleBuffer,true);
}
private void OnTick(object sender, EventArgs e)
{
if (current > maxSize)
{
current = 10F;
}
// 把字体加大1.0
current += step;
// 强制客户区重新绘制.
Invalidate();
}
///
/// 通过重写这个方法,可以在窗体客户区中进行绘制.
///
///
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics gra = e.Graphics;
gra.Clear(Color.White);
// 得到客户区的宽和高.
int width = ClientRectangle.Width;
int height = ClientRectangle.Height;
// 构建出绘制要用的字体.
Font font = new Font("微软雅黑", current);
Color color = Color.Lime;
// 计算出文本绘制出来后宽,高各是多少.
SizeF sf = gra.MeasureString(text, font);
float x = (width - sf.Width) / 2F;
float y = (height - sf.Height) / 2F;
//
Brush brush = new SolidBrush(color);
// 绘制文本.
gra.DrawString(text, font, brush, new PointF(x, y));
brush.Dispose();
font.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}
}