111,044
社区成员
我尝试在pictureBox控件上绘图,下面是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private int x; //工人当前位置(x,y)
private int y;
public Rectangle myRectangle; //自己
public Graphics gr; //PicShow的Graphics对象
public Form1()
{
InitializeComponent();
}
private void drawimage()
{
myRectangle = new Rectangle(x, y, 80, 30);
gr = pictureBox1.CreateGraphics();
myRectangle.Show(gr);
}
private void Form1_Load(object sender, EventArgs e)
{
x = 10;
y = 370;
myRectangle = new Rectangle(x, y, 80, 30);
gr = pictureBox1.CreateGraphics();
myRectangle.Show(gr);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)//分析按键消息
{
//向上
case Keys.Left:
if (x >= 5)
{
x -= 5;
pictureBox1.Refresh();
myRectangle = new Rectangle(x, y, 80, 30);
myRectangle.Show(gr);
gr.Dispose();
// drawimage();
}
break;
case Keys.Right:
if (x <= 315)
x += 5;
pictureBox1.Refresh();
myRectangle = new Rectangle(x, y, 80, 30);
myRectangle.Show(gr);
gr.Dispose();
// drawimage();
break;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
myRectangle = new Rectangle(x, y, 80, 30);
gr = pictureBox1.CreateGraphics();
myRectangle.Show(gr);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace WindowsFormsApp2
{
public class Rectangle
{
public int x;//坐标
public int y;
public int width;//
public int height;
public int direction = 0; //方向,0表示停止,1表示向上走,2下,3左,4右
public System.Timers.Timer timer;//球的timer
//构造函数
public Rectangle(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
timer = new System.Timers.Timer();
timer.Interval = 30;
timer.AutoReset = true;
}
public Rectangle() { }
//将自己画到gr上
public void Show(Graphics gr)
{
Rectangle rt = new Rectangle(x, y, width, height);
Pen mypen = new Pen(Color.Red, 3);
gr.DrawRectangle(mypen, x, y, width, height);
}
}
}
Form1_Load中的代码无效,写在pictureBox1_Paint事件里的代码也没有会出图像,Keys.Right和Keys.Left键的代码可以显示图像,我看有的源码是把绘图放在 Form1_Load中,我尝试却不行。
放在 OnActivated 里绘图, Load 在窗口还没显示时就触发了。