美文网首页
TextView:Layout、TextPaint、FontMe

TextView:Layout、TextPaint、FontMe

作者: 蒸汽飞船 | 来源:发表于2018-04-24 16:23 被阅读41次

    附件已上传github:TextLocationHelper.java

    1.获取文字高度:

    Paint.FontMetrics fm = textPaint.getFontMetrics();
    textHeight = (int) (fm.bottom+fm.top);
    

    2.测量文字宽度:
    textPaint.measureText(mText);

    代码示例:

    TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 
    textPaint.setTextSize(12);
    textPaint.setColor(Color.BLUE);
    
    //PorterDuffColorFilter  lastPicWithMpore =
    //new PorterDuffColorFilter(Color.parseColor("#7f000000"), PorterDuff.Mode.SRC_ATOP);//灰色遮罩
    
    Paint.FontMetrics fm = textPaint.getFontMetrics();
    //获取文字高度
    textHeight = (int) (fm.bottom+fm.top);
    
    //测量文字宽度
    float textWidth = textPaint.measureText(mText); 
    int x_offset = (int) (getWidth()-textWidth)/2;
    if(x_offset<0){
        x_offset = 0;
    }
    int y_offset = (getHeight()-textHeight)/2;
    canvas.drawText(mText,x_offset,y_offset,textPaint);
    
    1. 根据坐标获取文字的offset:
    //x,y
    int line = layout.getLineForVertical(y);                  //根据纵坐标获取所对应的行
    int ofset = layout.getOffsetForHorizontal(line, x);  //根据行和横坐标获取文字的offset
    float lineRight = layout.getLineRight(line);            //获取该行最有边的距离(也就是横坐标)
    

    4.根据文字offset获取该文字处的坐标

    //根据字符所在位置的偏移量计算该字符左下角的坐标,坐标是相对于该TextView的
    private static int[] getFixXYByTextviewOffset(TextView tv, int offset) {
        Layout layout = tv.getLayout();
        if (layout != null) {
            int line = layout.getLineForOffset(offset);    //根据文字offset获取所在的行
            int base = layout.getLineBottom(line);    
            //修正纵坐标用,暂未使用
            int lineYxiuZheng = layout.getLineDescent(line);
    
            int relativeX = (int) layout.getPrimaryHorizontal(offset) - tv.getScrollX(); // x
            int relativeY  = base - tv.getScrollY(); // y
            return new int[]{relativeX,relativeY};
        }
        return null;
    }
    
    1. 判断offset是否在行的结尾
    /**返回该offset是否在行的结尾*/
    private static boolean isEndOfLineOffset(TextView tv,int offset) {
        if (offset > 0) {
            return tv.getLayout().getLineForOffset(offset) ==
                    tv.getLayout().getLineForOffset(offset - 1) + 1;
        }
        return false;
    }
    

    相关文章

      网友评论

          本文标题:TextView:Layout、TextPaint、FontMe

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