检测图片框边缘C#

时间:2016-05-15 10:42:08

标签: c# picturebox

我正在创建一个简单的弹跳球应用程序,它使用计时器弹回图片框两侧的球,我遇到的麻烦就是它从底部和右边反弹很好图片框的一侧但没有从顶部或左侧反弹,我不知道为什么,如果你想知道,球的大小是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;
        }

    }
}

如果有人能看到我的问题,那么请让我知道,非常感谢!

1 个答案:

答案 0 :(得分:1)

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

所以你的代码应该是这样的:

  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

        }