【问题标题】:Android - How to get the coordinates of a character in a textviewAndroid - 如何在文本视图中获取字符的坐标
【发布时间】:2019-07-23 13:59:40
【问题描述】:

是否可以从 Android 的 TextView 中的字符获取 x 坐标? 我不是在找TextView本身的坐标,我要的是TextView中最后一个字符的坐标(多行)

提前致谢

【问题讨论】:

标签: android char textview character coordinates


【解决方案1】:

Java 解决方案

这里是如何获取特定字符的x y 坐标。 offset 是 textView 字符串中所需字符的索引。这些坐标是相对于父容器的

Layout layout = textView.getLayout();
if (layout == null) { // Layout may be null right after change to the text view
    // Do nothing
}

int lineOfText = layout.getLineForOffset(offset);
int xCoordinate = (int) layout.getPrimaryHorizontal(offset);
int yCoordinate = layout.getLineTop(lineOfText);

Kotlin 扩展函数

如果您希望多次使用它:

fun TextView.charLocation(offset: Int): Point? {
    layout ?: return null // Layout may be null right after change to the text view

    val lineOfText = layout.getLineForOffset(offset)
    val xCoordinate = layout.getPrimaryHorizontal(offset).toInt()
    val yCoordinate = layout.getLineTop(lineOfText)
    return Point(xCoordinate, yCoordinate) 
}

注意:为确保布局不为空,您可以在 Java 中调用 textview.post(() -> { /* get coordinates */ }) 或在 Kotlin 中调用 textview.post { /* get coordinates */ }

【讨论】:

    【解决方案2】:

    用途:

    layout.getPrimaryHorizontal(int offset)
    

    使用简单。您只需使用它使用的文本长度来遍历布局。

    它将返回 Character 的 x 。所以我仍然从 layout.getLineTop() 得到线路。顺便说一句,如果您使用的是 layout.getLineTop() ,请注意有一些奇怪的行为,可能是一个错误。

    【讨论】:

      【解决方案3】:

      给定一个包含一个或多个段落的跨度,尝试让整个跨度的最后一个字符不起作用。是否有其他方法可以获得与 getPrimaryHorizo​​ntal() 相同的结果?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-08
        • 1970-01-01
        • 2014-08-27
        • 2014-02-14
        • 1970-01-01
        相关资源
        最近更新 更多