draw text “ellipsized” to a canvas

后端 未结 2 1176
星月不相逢
星月不相逢 2021-01-07 23:38

I need to draw text to a canvas (of a custom view), and need to first trim it to a maximum width, adding an ellipsis at the end if necessary. I see you can do it for a Text

相关标签:
2条回答
  • 2021-01-08 00:11

    Take a look at TextUtils.ellipsize(). I think it's exactly what you want. Basically you just tell it the amount of space available and using the other state information it will create the correct text for you. :)

    0 讨论(0)
  • 2021-01-08 00:13

    Here is an example:

    TextPaint textPaint = new TextPaint();//The Paint that will draw the text 
    textPaint.setColor(Color.WHITE);//Change the color if your background is white!
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setAntiAlias(true);
    textPaint.setTextSize(20);
    textPaint.setTextAlign(Paint.Align.LEFT);
    textPaint.setLinearText(true);
    
    Rect b = getBounds(); //The dimensions of your canvas
    int x0 = 5;           //add some space on the left. You may use 0
    int y0 = 20;          //At least 20 to see your text
    int width = b.getWidth() - 10; //10 to keep some space on the right for the "..."
    CharSequence txt = TextUtils.ellipsize("The text", textPaint, width, TextUtils.TruncateAt.END);
    canvas.drawText(txt, 0, txt.length(), x0, y0, textPaint);
    
    0 讨论(0)
提交回复
热议问题