如何在 Corona SDK 中为单词添加矩形边框?

在 Corona SDK 中,如何准确地确定某一行内单词的框架大小呢?换句话说,我想要在特定单词的上方添加一个矩形,我试过使用 webview 和 mark 标记来完成,但是在 iOS 上 webview 会一直闪烁,所以 webview 的解决方案被取消了。

highlight

我已经手动添加了矩形框架到这个单词上,但是有没有更好的方法来确定一个单词并知道它的框架大小,以便我可以高亮它,并将矩形移动到下一个单词?我使用的字体是 Arial,且不是等宽字体。

          local myRect = display.newRect(20,165,32,12.5)
          myRect.alpha = 0.5
          myRect:setFillColor(1,1,0)
          myRect.anchorX = 0

          local myString = "Word is highlighted"
          local line = display.newText(myString,  0,165, "Arial", 12.5)
          line.anchorX = 0
          line.x = 20

非常感谢。

点赞
用户3041972
用户3041972

尝试这个。

local player2 = display.newText("test221234567890", 210, 210 )
player2:setFillColor( 0.6, 0.4, 0.8 )

local myRectangle = display.newRect( player2.x, player2.y, player2.width, player2.height )
myRectangle.strokeWidth = 3
myRectangle:setFillColor( 0.5 )
myRectangle:toBack()
2016-09-11 11:31:56
用户4567755
用户4567755

如果我是你,我只会为此编写一个额外的函数。像这样:

function highlightedText(pre, high, post, x, y, font, size)
    local text = display.newText("", x, y, font, size)
    local dx, rectangle = 0
    if pre then
        local t = display.newText(pre, 0, 0, font, size)
        text.text = pre
        dx = t.width
        -- 根据Corona文档,我们需要添加下面这行代码
        text.anchorX = 0 text.x = x text.y = y
        t:removeSelf()
    end
    if high then
        local t = display.newText(high, 0, 0, font, size)
        rectangle = display.newRect(x+dx, y, t.width, t.height)
        rectangle:toBack()
        text.text = text.text .. high
        -- 根据Corona文档,我们需要添加下面这行代码
        text.anchorX = 0 text.x = x text.y = y
        t:removeSelf()
    end
    if post then
        text.text = text.text .. post
        -- 根据Corona文档,我们需要添加下面这行代码
        text.anchorX = 0 text.x = x text.y = y
    end
    return text, rectangle, dx -- 如果要移动整个文本和矩形,则传递“dx”
end

local text, rect, _ = highlightedText("The", "word", "is highlighted.", 10, 10, "Arial", 12.5)

rect.alpha = 0.5
rect:setFillColor(1,1,0)
rect.strokeWidth = 3

text:setFillColor(1,1,1)

我不是Corona的专家,但这应该可以适用于单行静态文本。

2016-09-11 14:07:01