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

问题描述 投票:0回答:1

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

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

lua corona
1个回答
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 
© www.soinside.com 2019 - 2024. All rights reserved.