自定义View保持文字居中

2017-02-09 0 条评论 257 次阅读 1 人点赞

此时我是相对于整个View居中所以就谢了getWidth()/2``canvas.drawText("this is a test", getWidth() / 2, baseLineY, textPaint); Y轴居中要给予baseLine,这个baseLine的概念就是字符串字的最底部.如果此值传入getHeight()/2的话那么baseLine的基点就在View的中间,从而导致文字居中偏上.如下图.绿色的线是居中的

IMG_20170209_175335.jpg

此时的代码是这样的:

canvas.drawText("this is a test", getWidth() / 2, /*baseLineY*/getHeight() / 2, textPaint);

如果要让文字绝对居中,就要计算出文字的baseLine调整策略,要根据以下信息:

 Paint textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(DensityUtil.dip2px(20));
        textPaint.setStyle(Paint.Style.FILL);
       textPaint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float top = fontMetrics.top;
        float bottom = fontMetrics.bottom;
        Log.d(TAG, "getWidth(): " + getWidth() + " getHeight() " + getHeight() +" top "+top +" bottom "+bottom);

此时这段代码打印出来的结果是: getWidth(): 400 getHeight() 200 top -42.246094 bottom 10.839844 top就是baseLine到字体上方的距离.bottom亦然. 由此得出 字体的高度-基线到字体底部 = 字体中心点(基线到底部的距离是没有字体存在的) 得出公式为:view高度的一半-字体中心点为 字体应该居中的点. 完整代码如下:

 Rect rect = new Rect(0, 0, getWidth(), getHeight());
        Log.d(TAG, "onDraw: " + rect);
        Paint textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(DensityUtil.dip2px(20));
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextAlign(Paint.Align.CENTER);
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float top = fontMetrics.top;
        float bottom = fontMetrics.bottom;
        Log.d(TAG, "getWidth(): " + getWidth() + " getHeight() " + getHeight() / 2 + " top " + top + " bottom " + bottom);
        int baseLineY = (int) (getHeight() / 2 - top / 2 - bottom / 2);
        Log.d(TAG, "onDraw: " + baseLineY + " rect.centerY() " + rect.centerY());
        canvas.drawText("this is a test", getWidth() / 2, baseLineY/*getHeight() / 2*/, textPaint);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        canvas.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2, paint);

最终效果如图:

IMG_20170209_183015.jpg

TestSmirk

这个人太懒什么东西都没留下

文章评论(0)