Draw text inside android circle

后端 未结 3 579
感动是毒
感动是毒 2021-02-06 15:31
public static Bitmap drawCircle(int width,int height, int borderWidth) {
    Bitmap canvasBitmap = Bitmap.createBitmap( 350, 350, Bitmap.Config.ARGB_8888);
    BitmapSha         


        
相关标签:
3条回答
  • 2021-02-06 16:03

    You could try this.

        private Paint paint;
        private Paint circlePaint;
    
        paint = new Paint();
        circlePaint = new Paint();
    
        paint.setColor(Color.WHITE);
        paint.setTextSize(18f);
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);
    
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
    
        circlePaint.setColor(Color.RED);
        circlePaint.setAntiAlias(true);
    
        canvas.drawCircle(-3, 15 - (bounds.height() / 2), bounds.width() + 5, circlePaint);
    
        canvas.drawText(text, -3, 15, paint);
    

    Note : (-3,15) is the starting co-ordinates to draw the text and (+5) is the padding.

    This should give you an output like the notification badge here -> sample

    0 讨论(0)
  • 2021-02-06 16:11

    I had a similar requirement where needed text drawn in the centre of a circle.

    Here's how I did it (within my customview's onDraw) albeit it similar to @Anoop's answer.

    //draw circle
    canvas.drawCircle(xPos,yPos,mCircleSize, mCirclePaint);
    
    mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    
    //this ensures X alignment
    mTextPaint.setTextAlign(Paint.Align.CENTER);
    
    // Measure the text rectangle to get the height        
    Rect result = new Rect();
    mTextPaint.getTextBounds(marker.label, 0, marker.label.length(), result);
    //take half the height as the offset
    int yOffset = result.height()/2;
    
    //add offset to ensure Y is aligned center
    canvas.drawText(marker.label, xPos, yPos+yOffset, mTextPaint);
    
    0 讨论(0)
  • 2021-02-06 16:13

    Idea: Use a simple TextView component.

    Then create this custom shape:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
        android:shape="oval">
        <corners android:radius="10dip"/>
        <stroke android:color="@android:color/black" android:width="2dip"/>
        <solid android:color="@android:color/transparent"/>
    </shape>
    

    And finally set this shape to be the background of your textview.

    For more suggestions check this link: Android draw circle around Text

    0 讨论(0)
提交回复
热议问题