自定义view实现圆中心显示文字

自定义view实现:画一个矩形 然后画一个圆 再在圆中心显示文字,效果如下


 RectF rect = new RectF(100,100,500,500);//画一个矩形
        Paint mPaint = new Paint();
        mPaint.setColor(Color.GRAY);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRect(rect, mPaint);

        //设置画笔的样式,空心STROKE
        mPaint.setStyle(Paint.Style.FILL);
        //设置抗锯齿
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.RED);
        canvas.drawCircle(rect.centerX(),rect.centerY(),150,mPaint);

        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(50);
        mPaint.setStyle(Paint.Style.FILL);
        //该方法即为设置基线上那个点究竟是left,center,还是right  这里我设置为center
        mPaint.setTextAlign(Paint.Align.CENTER);

        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
        float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom

        int baseLineY = (int) (rect.centerY() - top/2 - bottom/2);//基线中间点的y轴计算公式

        canvas.drawText("小学",rect.centerX(),baseLineY,mPaint);

猜你喜欢

转载自blog.csdn.net/xiaoyi848699/article/details/79708925