美文网首页
自定义View文字BaseLine问题

自定义View文字BaseLine问题

作者: CalvinNing | 来源:发表于2017-03-21 09:58 被阅读178次
        //getTextBound获得的是包裹当前字体的最小矩形
        mTextPaint.getTextBounds(mShowText,0,mShowText.length(), mBounds);//Rect mBounds
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        //fontMetrics.top的值是负值
        //fontMetrics.bottom 的值是正值
        //本来是baseline居中,如果要是整体字居中,则应该如下计算
        //baseLine = getHeight()/2+(-fontMetrics.top-fontMetrics.bottom)/2;
        float baseLine = getHeight()/2-(fontMetrics.top+fontMetrics.bottom)/2;
        canvas.drawText(text, getWidth() / 2 - mBounds.width() / 2, baseLine, mPaint);
/**
     * Draw the text, with origin at (x,y), using the specified paint. The
     * origin is interpreted based on the Align setting in the paint.
     *
     * @param text  The text to be drawn
     * @param x     The x-coordinate of the origin of the text being drawn
     * @param y     The y-coordinate of the baseline of the text being drawn
     * @param paint The paint used for the text (e.g. color, size, style)
     */
    public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {
        native_drawText(mNativeCanvasWrapper, text, 0, text.length(), x, y, paint.mBidiFlags,
                paint.getNativeInstance(), paint.mNativeTypeface);
    }

相关文章

网友评论

      本文标题:自定义View文字BaseLine问题

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