object:localToContent()

类型 函数
对象 DisplayObject
display.*
返回值 数字
修订 版本 2024.3703
关键词 显示对象, 坐标
另请参阅 object.contentToLocal
object.contentBounds

概述

将对象的给定 **x** 和 **y** 坐标映射到内容(舞台)坐标。

此方法对于比较不同组中显示对象的位置非常有用。当显示对象插入到组中时,该对象的核心 **x** 和 **y** 属性是相对于其组(父级)而不是内容(舞台)的。object:localToContent() 可用于返回对象的实际内容坐标,与其父组无关。

此方法也可用于确定对象上特定偏离中心点的 Content 坐标,即使是已旋转或缩放的对象。例如,您可以传递相对于对象中心的 **x** 和 **y** 值,并检索该点在内容(舞台)坐标中的特定位置。请参阅下面的示例代码。

请注意,此方法类似于 object.contentBounds,但它返回一个特定的坐标点,而不是对象的边界限制。

语法

object:localToContent( x, y )
x, y (必需)

数字 相对于显示对象中心点的坐标。点 0,0 指的是对象的中心点。

返回值

此函数返回相对于内容区域左上角位置的 **x** 和 **y** 内容坐标。

示例

-- Create a square
local square = display.newRect( 100, 100, 40, 40 )
square:setFillColor( 1 )

-- Create another square on top and rotate it 20 degrees
local redSquare = display.newRect( 100, 100, 40, 40 )
redSquare:setFillColor( 1, 0, 0, 0.6 )
redSquare.rotation = 20

local sqCenterX, sqCenterY = square:localToContent( 0, 0 )
print( "White square's center position in screen coordinates: ", sqCenterX, sqCenterY )

-- Get the content position of the white square's top-left corner
-- Using ( -20,-20 ) specifies the top left corner of the square, since it's 40x40 in size
local whiteTLX, whiteTLY = square:localToContent( -20, -20 )
print( "White square's top-left position in screen coordinates: ", whiteTLX, whiteTLY )

-- Get the content position of the red square's top-left corner, independent of its rotation
-- Using ( -20,-20 ) specifies the top left corner of the square, since it's 40x40 in size
local redTLX, redTLY = redSquare:localToContent( -20, -20 )
print( "Red square's top-left position in screen coordinates: ", redTLX, redTLY )