在Android中,如何将文本绘制到矩形的中心并根据需要进行裁剪?

13

我想在矩形框的中心(水平和垂直方向)绘制文本。如果有太多的文本无法适合矩形框,则应将其裁剪。

我尝试按照 这个例子进行操作,但没有成功。

有什么想法吗?


请查看这个链接,它与您所需的有些相似:http://stackoverflow.com/questions/13285510/how-to-overlay-image-with-multiline-texttext-will-be-in-center-of-the-canvas/13287621#13287621 - Abhishek Nandi
试试这个,对我有用:https://dev59.com/OWgu5IYBdhLWcg3wuJWF - fabio.cappelli.spot
这对我有用,你也可以试试。https://dev59.com/OWgu5IYBdhLWcg3wuJWF - fabio.cappelli.spot
2个回答

12

试一试

private void drawRectText(String text, Canvas canvas, Rect r) {

    textPaint.setTextSize(20);
    textPaint.setTextAlign(Align.CENTER);
    int width = r.width();

    int numOfChars = textPaint.breakText(text,true,width,null);
    int start = (text.length()-numOfChars)/2;
    canvas.drawText(text,start,start+numOfChars,r.exactCenterX(),r.exactCenterY(),textPaint);
}

这会将文本居中对齐,但仅在水平方向上。因此问题是如何在垂直方向上实现它。 - ddmytrenko

5

这个函数对我起作用了。

private void drawDigit(Canvas canvas, int textSize,  float cX, float cY, int color, String text) {
        Paint tempTextPaint = new Paint();
        tempTextPaint.setAntiAlias(true);
        tempTextPaint.setStyle(Paint.Style.FILL);

        tempTextPaint.setColor(color); 
        tempTextPaint.setTextSize(textSize); 

        float textWidth = tempTextPaint.measureText(text);
        //if cX and cY are the origin coordinates of the your rectangle 
        //cX-(textWidth/2) = The x-coordinate of the origin of the text being drawn 
        //cY+(textSize/2) =  The y-coordinate of the origin of the text being drawn 

        canvas.drawText(text, cX-(textWidth/2), cY+(textSize/2), tempTextPaint);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接