美文网首页
获取某个字符在TextView中的位置(坐标)

获取某个字符在TextView中的位置(坐标)

作者: feifei_fly | 来源:发表于2019-04-12 11:35 被阅读0次

一、普通TextView 获取某个字符相对于TextView的坐标


/**
     * 获取TextView某一个字符的坐标
     *
     * @parms tv
     * @parms index 字符下标
     * @return 返回的是相对坐标
     */
    private int getTextViewSelectionBottomY(TextView tv,int index) {
        Layout layout = tv.getLayout();
        Rect bound = new Rect();
        int line = layout.getLineForOffset(index);//获取字符在第几行
        layout.getLineBounds(line, bound);//获取该行的Bound区域
        int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
        int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
        float xAxisLeft = layout.getPrimaryHorizontal(index);//字符左边x坐标(相对于TextView)
        float xAxisRight = layout.getSecondaryHorizontal(index);//字符右边x坐标(相对于TextView)
 
        return yAxisBottom;
 

二、获取ClickSpan 点击的坐标

// 计算点击的单词的坐标,首先计算单词在整个短文中的起始位置,即可获取到该单词的x偏移。通过起始位置
    // 还可以获取该单词所在的行索引。进而可以获取该行所在的矩形区域。即可获取到该单词的y偏移。在计算
    // padding和scroll的影响,最终可以获得点击位置的屏幕坐标
    private void calcClickPosition(View widget, int[] pos, ClickableSpan clickableSpan) {
        TextView textView = (TextView) widget;
        Rect parentTextViewRect = new Rect();

        Spanned spannedString = (Spanned) textView.getText();
        // 获取点击单词的起始索引
        int start = spannedString.getSpanStart(clickableSpan);
        Layout textViewLayout = textView.getLayout();
        // 获取点击单词所在的行数
        int lineOffset = textViewLayout.getLineForOffset(start);
        // 获取点击单词所在的x坐标
        double clickX = textViewLayout.getPrimaryHorizontal(start);
        // 获取点击单词所在一行的矩形
        textViewLayout.getLineBounds(lineOffset, parentTextViewRect);
        int[] parentTextViewLocation = {0, 0};
        // 获取TextView左上角的坐标
        textView.getLocationOnScreen(parentTextViewLocation);
        // 加入scroll和padding的偏移的计算
        parentTextViewRect.bottom += parentTextViewLocation[1] + textView.getCompoundPaddingTop()- textView.getScrollY();

        parentTextViewRect.left += parentTextViewLocation[0] + clickX + textView.getCompoundPaddingLeft() - textView.getScrollX();
        pos[0] = parentTextViewRect.left;

        int lineHeight = 20;
        pos[1] = (int) (parentTextViewRect.bottom - textView.getLineSpacingExtra() - textView.getLineSpacingMultiplier() * lineHeight);
    }

相关文章

网友评论

      本文标题:获取某个字符在TextView中的位置(坐标)

      本文链接:https://www.haomeiwen.com/subject/cfaqwqtx.html