object:contentToLocal()

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

概述

将给定的内容(舞台)坐标中的 **x** 和 **y** 值映射到目标对象的局部坐标(中心点)。

语法

object:contentToLocal( xContent, yContent )
xContent (必填)

数字. 内容(显示)空间中的 **x** 坐标。

yContent (必填)

数字. 内容(显示)空间中的 **y** 坐标。

返回值

此函数返回对象局部坐标空间中给定值的 **x** 和 **y** 坐标。 返回的值是相对于 显示对象 中心点的,如果给定点位于对象的中心点上方或左侧,则这些值将为负数。

示例

-- Rectangle that fills screen
local rect = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
rect.x = display.contentCenterX ; rect.y = display.contentCenterY
rect.strokeWidth = 4 ; rect:setStrokeColor( 1, 0, 0 )
rect:setFillColor( 0, 0, 0 )

-- Create text objects to display content and local coordinates
local contentText = display.newText( "", 0, 0, display.nativeSystemFont, 16 )
local localText = display.newText( "", 0, 0, display.nativeSystemFont, 16 )
localText.anchorX = 0 ; localText.anchorY = 0
contentText.anchorX = 0 ; contentText.anchorY = 0
 
function showCoordinates( event )
    -- Get x and y of touch event in content coordinates
    local contentX, contentY = event.x, event.y

    -- Convert to local coordinates of 
    local localX, localY = event.target:contentToLocal( contentX, contentY )        

    -- Display content and local coordinate values
    contentText.text = "CONTENT: " .. tostring(contentX) .. ", " .. tostring(contentY)
    localText.text = "LOCAL: " .. tostring(localX) .. ", " .. tostring(localY)
    contentText.x, contentText.y = event.x+20, event.y
    localText.x, localText.y = event.x+20, event.y+20
    localText.anchorX = 0 ; localText.anchorY = 0
    contentText.anchorX = 0 ; contentText.anchorY = 0
    return true
end

rect:addEventListener( "touch", showCoordinates )