美文网首页
Android Canvas drawText实现中文垂直居中

Android Canvas drawText实现中文垂直居中

作者: proud2008 | 来源:发表于2017-08-02 13:23 被阅读23次

    http://blog.csdn.net/hursing/article/details/18703599

    @Override  
    public void onDraw (Canvas canvas) {  
        Rect targetRect = new Rect(50, 50, 1000, 200);  
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);  
        paint.setStrokeWidth(3);  
        paint.setTextSize(80);  
        String testString = "测试:ijkJQKA:1234";  
        paint.setColor(Color.CYAN);  
        canvas.drawRect(targetRect, paint);  
        paint.setColor(Color.RED);  
        FontMetricsInt fontMetrics = paint.getFontMetricsInt();  
        int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;  
        // 下面这行是实现水平居中,drawText对应改为传入targetRect.centerX()  
        paint.setTextAlign(Paint.Align.CENTER);  
        canvas.drawText(testString, targetRect.centerX(), baseline, paint);  
    }  
    

    相关文章

      网友评论

          本文标题:Android Canvas drawText实现中文垂直居中

          本文链接:https://www.haomeiwen.com/subject/erwelxtx.html