How to draw text inside custom view?

2020-07-13 07:45发布

I have created custom view to draw a custom speech bubble inside and I want put some text on custom view. I use drawTextOnPath but it doesn't work right, I want the text to appear line by line.

Custom View - Speech Bubble

Paint paint = new Paint();

paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setStrokeWidth(2);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);      
paint.setPathEffect(new CornerPathEffect(15) );  
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setDither(true);
paint.setShader(new LinearGradient(0, 0, 0, getHeight(), Color.BLACK, Color.WHITE,
                                                           Shader.TileMode.MIRROR));
Path path = new Path();         
paint.setShadowLayer(4, 2, 2, 0x80000000);
path.moveTo(myPath[0].x, myPath[0].y);
for (int i = 1; i < myPath.length; i++){
    path.lineTo(myPath[i].x, myPath[i].y);                  
}
path.close();
canvas.clipPath(path);
canvas.drawPath(path, paint);
canvas.save();
paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawTextOnPath(MessageBody, path, 10, 10, paint);

Thanks.

2条回答
趁早两清
2楼-- · 2020-07-13 08:46

something like this?

Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
...
//tell the paint of the new color
paint.setColor(android.R.color.black);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);

edit:

then why not something like this

Path path = new Path();
path.addCircle(width/2, height/2, radius, Path.Direction.CW);

Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
canvas.drawTextOnPath("Some Text", path, 0, 0, paint);

edit nr2:

why not add a rect?

path.addRect(left, top, right, bottom, Direction.CW);

or

path.addRect(rect, Direction.CW);
查看更多
走好不送
3楼-- · 2020-07-13 08:50

I created a rectangle in the speech bubble like so

Rect rcText;
rcText = new Rect(rcBounds);//rcBounds is y speech bubble rect
canvas.save();

Limited the draw area

canvas.cliprect(rect);

And draw the text inside the speech bubble like this

canvas.drawtext(mytext,rect.left,rect.top,paint);
canvas.restore();

Thanks mc_fish.

查看更多
登录 后发表回答