0
我現在正在使用圖形,並且正在嘗試創建一個隨關鍵事件一起移動的矩形。 下面是代碼:當方法調用時,矩形不會向上移動
類來創建矩形:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snake
{
class RectangleClass
{
// private Rectangle _rectangle;
private int _positionX;
private int _positionY;
private int _height;
private int _width;
public RectangleClass(int positionX, int positionY, int height, int width)
{
_positionX = positionX;
_positionY = positionY;
_height = height;
_width = width;
}
public int PositionX
{
get
{
return _positionX;
}
set
{
_positionX = value;
}
}
public int PositionY
{
get
{
return _positionY;
}
set
{
_positionY = value;
}
}
public int Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
public int Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public Rectangle CreateRectangle()
{
Rectangle rectangle = new Rectangle(PositionX, PositionY, Width, Height);
return rectangle;
}
public int MoveYUpWard()
{
return PositionY += 10;
}
public int MoveYDownWard()
{
return PositionY -= 10;
}
}
}
和形式:
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 Snake
{
public partial class Form1 : Form
{
RectangleClass rc;
public Form1()
{
InitializeComponent();
rc = new RectangleClass(30, 90, 50, 50);
}
private Graphics g;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (g == null)
{
g = this.CreateGraphics();
}
Pen pen = new Pen(Color.Blue, 10);
g.DrawRectangle(pen, rc.CreateRectangle());
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
MessageBox.Show("UP");
//Sets position y to 100
rc.MoveYUpWard();
}
}
我已調試的代碼,並且該方法MoveYUpWard()不改變的位置當按下箭頭鍵時,矩形的位置相同。
我將不勝感激。
不要存儲'Graphics'實例。相反,使用'e.Graphics'。 – SLaks
你確定paint事件被觸發嗎? –
表單不知道重繪 - 調用它無效。 –