如何在corona sdk中将对象锚定在矩形内?

时间:2017-12-31 16:06:22

标签: lua corona

我正在尝试在一个大矩形内部添加一个小矩形,如下图所示,但似乎没有任何效果。我想使用锚,但我不知道如何继续。我试图将小矩形放在较大矩形的右上角。任何建议都会非常有用!

local bigRectangle = display.newRect(200,200,320,400)
bigRectangle:setFillColor(0,0,1)
bigRectangle.x = _X
bigRectangle.y = _Y

local smallRectangle = display.newRect(200,200,20,20)
bigRectangle:setFillColor(255/255,255/255,0/255)

我想要完成的事情: enter image description here

1 个答案:

答案 0 :(得分:1)

它可以通过多种方式实现。最简单的方法是将锚点更改为(1, 0)。它要求两个对象具有相同的xy坐标:

local bigRectangle = display.newRect( 200, 200, 320, 400 )
bigRectangle.anchorX, bigRectangle.anchorY = 1, 0
bigRectangle:setFillColor( 0, 0, 1 )

local smallRectangle = display.newRect( 200, 200, 20, 20 )
smallRectangle.anchorX, smallRectangle.anchorY = 1, 0
smallRectangle:setFillColor( 255 / 255, 255 / 255, 0 / 255 )

更通用的方法使用显示对象的bounds属性:

local bigRectangle = display.newRect( 200, 200, 320, 400 )
    bigRectangle:setFillColor( 0, 0, 1 )
    bigRectangle.x = _X
    bigRectangle.y = _Y

    local smallRectangle = display.newRect( 200, 200, 20, 20 )
    smallRectangle:setFillColor( 255 / 255, 255 / 255, 0 / 255 )

    local bounds = bigRectangle.contentBounds
    smallRectangle.x = bounds.xMax - smallRectangle.width * smallRectangle.anchorX
    smallRectangle.y = bounds.yMin + smallRectangle.height * smallRectangle.anchorY