C# 检查对象是否越界 (GUI)
本文关键字:GUI 越界 是否 检查 对象 | 更新日期: 2023-09-27 17:57:20
我正在C# WFA中创建一个移动矩形。它可以毫无问题地移动,但它可能会离开我的 GUI,所以我需要检查我的矩形是否超出界限。我已经试过了,但它只适用于左上角。感谢您的帮助(我的窗口是400x400)
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 Object
{
public partial class Form1 : Form
{
enum Directions { Left, Right, Up, Down }
Directions _direct;
private int _x;
private int _y;
public Form1()
{
InitializeComponent();
_x = 50;
_y = 50;
_direct = Directions.Down;
}
private void Form1_Load(object sender, EventArgs e)
{
Invalidate();
}
private void form_paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Black, _x, _y, 70, 70);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_direct == Directions.Left)
{
_x -= 10;
checkPosition(_x, _y);
}
else if (_direct == Directions.Right)
{
_x += 10;
checkPosition(_x, _y);
}
else if (_direct == Directions.Down)
{
_y += 10;
checkPosition(_x, _y);
}
else if (_direct == Directions.Up)
{
_y -= 10;
checkPosition(_x, _y);
}
Invalidate();
checkPosition(_x, _y);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
_direct = Directions.Left;
}
else if (e.KeyCode == Keys.Right)
{
_direct = Directions.Right;
}
else if (e.KeyCode == Keys.Up)
{
_direct = Directions.Up;
}
else if (e.KeyCode == Keys.Down)
{
_direct = Directions.Down;
}
}
private void checkPosition(int x, int y) {
if (x < 0) {
_x = 0;
}
else if (y < 0) {
_y = 0;
}
else if ((x + 70) > 400) { _x = 330; }
else if ((y+70)>400) {_y=330;}
}
}
}
如果矩形和客户端矩形之间的交集是矩形,则矩形包含在客户端矩形中。使用此检查:
// rectangle is your rectangle
bool outOfBounds=!(Rectangle.Intersect(ClientRectangle, rectangle).Equals(rectangle))