Android: Creating a Circular TextView?

后端 未结 11 1594
我在风中等你
我在风中等你 2020-12-04 08:53

My current simple XML is below, however i would like the 3 TextViews within it to be circular, rather than rectangular.

How can I change my code to do so?

         


        
11条回答
  •  遥遥无期
    2020-12-04 09:45

    The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.

    Here is the code of custom TextView

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class CircularTextView extends TextView
    {
    private float strokeWidth;
    int strokeColor,solidColor;
    
    public CircularTextView(Context context) {
        super(context);
    }
    
    public CircularTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    
    @Override
    public void draw(Canvas canvas) {
    
        Paint circlePaint = new Paint();
        circlePaint.setColor(solidColor);
        circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
    
        Paint strokePaint = new Paint();
        strokePaint.setColor(strokeColor);
        strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
    
        int  h = this.getHeight();
        int  w = this.getWidth();
    
        int diameter = ((h > w) ? h : w);
        int radius = diameter/2;
    
        this.setHeight(diameter);
        this.setWidth(diameter);
    
        canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);
    
        canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);
    
        super.draw(canvas);
    }
    
    public void setStrokeWidth(int dp)
    {
        float scale = getContext().getResources().getDisplayMetrics().density;
        strokeWidth = dp*scale;
    
    }
    
    public void setStrokeColor(String color)
    {
        strokeColor = Color.parseColor(color);
    }
    
    public void setSolidColor(String color)
    {
        solidColor = Color.parseColor(color);
    
    }
    }
    

    Then in your XML, give some padding and make sure its gravity is center

    
    

    And you can set the stroke width

    circularTextView.setStrokeWidth(1);
    circularTextView.setStrokeColor("#ffffff");
    circularTextView.setSolidColor("#000000");
    

提交回复
热议问题