canvas.DrawText让文字真正居中显示

来源:互联网 发布:福州seo服务 编辑:程序博客网 时间:2024/05/21 08:35

canvas.drawColor(getResources().getColor(R.color.colorPrimary));        super.onDraw(canvas);        float x = this.getX();        float y = this.getY();        int w = this.getWidth();        int h = this.getHeight();        Log.e("x", String.valueOf(x));        Log.e("y", String.valueOf(y));        Log.e("x+w/2", String.valueOf(x + w / 2));        Log.e("y+h/2", String.valueOf(y + h / 2));        Paint paint = new Paint();        Rect rect = new Rect();        paint.setTextAlign(Paint.Align.LEFT);//        paint.setColor(getResources().getColor(R.color.white));        paint.getTextBounds("click to scale", 0 , "click to scale".length(), rect);        paint.setAntiAlias(true);
Paint.FontMetrics metricsInt = paint.getFontMetrics();//        canvas.drawText("click to scale",(getMeasuredWidth() - rect.width()) / 2,(getMeasuredHeight() - metricsInt.descent - metricsInt.ascent) / 2,paint);        /**        * because param y is not the text show in center,but the baseline ,so we must set the baseline instead of text to display in center        * */        canvas.drawText("click to scale",(getMeasuredWidth() - rect.width()) / 2,(getMeasuredHeight() - (metricsInt.descent + metricsInt.ascent)) / 2,paint);



参考:http://blog.csdn.net/lovexieyuan520/article/details/43153275


源码下载:git@github.com:edwinsnao/AnimationDemo.git

0 0