检测图片框边缘 C#

Detect picture box Edges C#

我正在创建一个简单的弹跳球应用程序,它使用计时器来弹跳图片框两侧的球,我遇到的问题是它从图片框的底部和右侧弹跳得很好图片框,但不会从顶部或左侧弹起,我不确定为什么,如果你想知道,球的大小是 30

它的代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace Ball
{
    public partial class Form1 : Form
    {
        int x = 200, y = 50;        // start position of ball
        int xmove = 10, ymove = 10; // amount of movement for each tick

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void pbxDisplay_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;      // get a graphics object

              // draw a red ball, size 30, at x, y position
            g.FillEllipse(Brushes.Red, x, y, 30, 30);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            x += xmove;             // add 10 to x and y positions
            y += ymove;       
            if(y + 30 >= pbxDisplay.Height)
            {
                ymove = -ymove;
            }
            if (x + 30 >= pbxDisplay.Width)
            {
                xmove = -xmove;
            }
            if (x - 30 >= pbxDisplay.Width)
            {
                xmove = -xmove;
            }
            if (y - 30 >= pbxDisplay.Height)
            {
                ymove = -ymove;
            }
            Refresh();              // refresh the`screen .. calling Paint() again

        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled= false;
        }

    }
}

如果有人能看出我的问题所在,请告诉我,非常感谢!

嗯,你的边缘识别方法是错误的。左上角点得到坐标[0,0]。所以你应该检查 left 和 top 是否为零。不是宽度和高度。

因此您的代码应如下所示:

  private void timer1_Tick(object sender, EventArgs e)
        {
            x += xmove;             // add 10 to x and y positions
            y += ymove;       
            if(y + 30 >= pbxDisplay.Height)
            {
                ymove = -ymove;
            }
            if (x + 30 >= pbxDisplay.Width)
            {
                xmove = -xmove;
            }
            if (x - 30 <= 0)
            {
                xmove = -xmove;
            }
            if (y - 30 <= 0)
            {
                ymove = -ymove;
            }
            Refresh();              // refresh the`screen .. calling Paint() again

        }