调整矩形大小的条件失败

时间:2013-12-02 05:52:04

标签: android android-canvas android-view

我在尝试实现调整大小的矩形时发现以下代码失败:

 for(int i=0;i<colorBalls.size();i++)
    {
        int centerX=colorBalls.get(i).getX()+colorBalls.get(i).getWidthOfBall();
        int centerY=colorBalls.get(i).getY()+colorBalls.get(i).getHeightOfBall();
        double radCircle=Math.sqrt(Math.pow(x-centerX,2)+Math.pow(y-centerX, 2));
        if(radCircle<colorBalls.get(i).getWidthOfBall())
        {
            mBallID=colorBalls.get(i).getId();
            Log.d("RectangleView", "ID of ball selected "+mBallID);
            if(mBallID==1 || mBallID==3)
                mGroupID=2;
            else
                mGroupID=1;
            invalidate();
            break;
        }
    }

我知道,因为在以下代码中,只打印了Resizing balls 2 and 4,但我的Logcat中从未打印过另一个:

 colorBalls.get(mBallID).setX(x);
    colorBalls.get(mBallID).setY(y);
    if (mGroupID == 1) {
        Log.d("RectangleView","Resizing balls 2 and 4");
        colorBalls.get(1).setX(colorBalls.get(0).getX());
        colorBalls.get(1).setY(colorBalls.get(2).getY());
        colorBalls.get(3).setX(colorBalls.get(2).getX());
        colorBalls.get(3).setY(colorBalls.get(0).getY());
    }
    if(mGroupID==2)
    {
        Log.d("RectangleView", "Resizing balls 1 and 3");
        colorBalls.get(0).setX(colorBalls.get(1).getX());
        colorBalls.get(0).setY(colorBalls.get(3).getY());
        colorBalls.get(2).setX(colorBalls.get(3).getX());
        colorBalls.get(2).setY(colorBalls.get(1).getY());
    }
    invalidate();

我的代码是this

的第二个答案的实现

点以逆时针方式呈现,0表示最左边,1表示低于0,2表示与1相同,右边为3,3表示高于2。

编辑:

修改了代码:

int centerX=colorBalls.get(i).getX()+colorBalls.get(i).getWidthOfBall()/2;//here
        int centerY=colorBalls.get(i).getY()+colorBalls.get(i).getHeightOfBall()/2;//here
        double radCircle=Math.sqrt(Math.pow(x-centerX,2)+Math.pow(y-centerY, 2));//here
        if(radCircle<colorBalls.get(i).getWidthOfBall())
        {
            mBallID=colorBalls.get(i).getId();
            Log.d("RectangleView", "ID of ball selected "+mBallID);
            if(mBallID==1 || mBallID==3)
                mGroupID=2;
            else
                mGroupID=1;
            invalidate();
            break;

1 个答案:

答案 0 :(得分:0)

您的代码只有一些小的数学错误。在计算centerX / centerY时,您需要添加 half 的宽度/高度,如下所示:

int centerX = colorBalls.get(i).getX() + colorBalls.get(i).getWidthOfBall() / 2;
int centerY = colorBalls.get(i).getY() + colorBalls.get(i).getHeightOfBall() / 2;

并且,在计算半径时,您意外地从y坐标中减去了centerX而不是centerY。应该是:

double radCircle = Math.sqrt(Math.pow(x-centerX, 2) + Math.pow(y-centerY, 2));
相关问题