关闭

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

标签: androidcanvas
446人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:22720次
    • 积分:633
    • 等级:
    • 排名:千里之外
    • 原创:38篇
    • 转载:23篇
    • 译文:1篇
    • 评论:5条
    文章分类
    最新评论