Android 输出一个字符串,不管字体大小如何修改,始终屏幕水平居中

       //获取到屏幕的宽度
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        //获取到字的宽度
        String displayText = "中华人民共和国万岁!";
        float textWidth = paint.measureText(displayText);
        //计算字体出现的x轴
        float f = (width - textWidth) / 2;

        canvas.drawText("中华人民共和国万岁!", f, 500, paint);

效果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/li_2580/article/details/83065340