读书人

画图重绘疑义

发布时间: 2013-03-25 15:43:04 作者: rapoo

画图重绘疑问

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 面向对象小项目之飞机小游戏
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();


}
Plane pla = new Plane();//飞机对象
Bullet bul = new Bullet();//子弹对象
private void Form1_Load(object sender, EventArgs e)
{
pla.StartInit();
bul.StatInit();
}

private void timer1_Tick(object sender, EventArgs e)
{
pla.Move(panel1);
bul.Move(panel1);
this.Invalidate();

}

private void Form1_Paint(object sender, PaintEventArgs e)
{
pla.Draw(panel1, panel1.CreateGraphics());
bul.Draw(panel1, panel1.CreateGraphics());
bul.IsHit(pla, panel1);


}
/// <summary>
/// 鼠标点击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
bul.SatrtFire(e, panel1);
}


}
}

//子弹类的代码
namespace 面向对象小项目之飞机小游戏
{
class Bullet:GameObject
{
/// <summary>
/// 绘制子弹
/// </summary>
/// <param name="p"></param>


/// <param name="g"></param>
public override void Draw(Panel p, Graphics g)
{


g.FillEllipse(Brushes.Black ,this.X1, this.Y1, this.Size, this.Size);
}
/// <summary>
/// 子弹移动
/// </summary>
/// <param name="p"></param>
public override void Move(System.Windows.Forms.Panel p)
{
//if(this.Y1 < 0)
//{

//}
this.Y1 -= this.Speed;
}
/// <summary>
/// 初始化
/// </summary>
public void StatInit()
{
this.Speed = 5;
this.X1 = 0;
this.Y1 = 500;
this.Size = 40;

}
/// <summary>
/// 开始攻击
/// </summary>
public void SatrtFire(MouseEventArgs e,Panel p)
{
this.Y1 = p.Height;
this.X1 = e.Location.X;

}
/// <summary>
/// 是否打中飞机
/// </summary>
/// <param name="p"></param>
/// <param name="p1"></param>
public void IsHit(Plane p,Panel p1)
{
if (this.X1 == p.X1 || this.Y1 == p.Y1)
{
if (p.HitTimes < 3)


{
p.Glimmer(p1);
}
else
{
MessageBox.Show("哈哈!你打中飞机了!");
}
}
}

}
}




我的飞机图片可以正常重绘 可是子弹却还残留上次的 造成图片中的这样 修改多次无果
[解决办法]
private void Form1_Paint(object sender, PaintEventArgs e)
{
panel1.Refresh(); //加一句
pla.Draw(panel1, panel1.CreateGraphics());
bul.Draw(panel1, panel1.CreateGraphics());
bul.IsHit(pla, panel1);
}
[解决办法]
既然在panel1中重绘 你不应该使用Form1的paint事件,你应该使用panel1的重绘事件


private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
bul.Draw(g);
}


public override void Draw(Graphics g)
{
g.FillEllipse(Brushes.Black ,this.X1, this.Y1, this.Size, this.Size);
}
public override void Move(System.Windows.Forms.Panel p)
{
this.Y1 -= this.Speed;
p.Refresh();//自己控制刷新时机
}

以上写法应该能保证你在panel上重绘
[解决办法]
嗯,放到panel的OnPaint中

读书人网 >C#

热点推荐