如何在 Android java 中使用 Paint 和 Convas 绘制椭圆形(带圆角的矩形)作为文本背景

问题描述 投票:0回答:1

我正在尝试使用 Paint 根据其大小向我的文本添加椭圆形背景。我的代码中有一些问题。

  1. 我想画圆角的矩形而不是圆。
  2. 它的大小不会根据文本长度而改变。

到目前为止,这是我的代码:

Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(500, 280, conf);
Canvas canvas1 = new Canvas(bmp);
                        
Paint color = new Paint();
color.setTextSize(30);
color.setColor(Color.BLACK);

Paint clr2=new Paint();
clr2.setColor(Color.WHITE);
canvas1.translate(200/2f,100/2f);
canvas1.drawCircle(50,0, 50, clr2);
canvas1.drawText(new Random().nextInt()+" $", 0, 0, color);`

当前成绩:

预期结果:

java android paint bitmapfactory oval
1个回答
0
投票
  1. 如果要绘制圆角矩形:

    Canvas.drawRoundRect(RectF(),10f,10f,Paint())
    
  2. 对于每个文本,你可以得到文本绑定(一个矩形一个圆形文本),然后用圆角绘制这个矩形:

     String text = "hello";
    Rect rectText = new Rect(); 
    paint.getTextBounds(text, 0, text.length(), rectText);
    canvas.drawRoundRect(rectText.left,rectText.top,rectText.right,rectText.bottom,radius,radius,paint);
    
© www.soinside.com 2019 - 2024. All rights reserved.