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

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

阅读更多
文章标签: android canvas
个人分类: Android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭