How to draw a circle with animation in android with circle size based on a value

前端 未结 3 1965
眼角桃花
眼角桃花 2020-11-29 16:42

I want to develop a custom component which draws part of the circle based on different values. e.g draw 1/4 cirle, 1/2 circle etc. The component needs to be animated to disp

3条回答
  •  渐次进展
    2020-11-29 17:11

    As extra from @JohnCordeiro answer. I have added parameters from xml to reuse the circle and to fill the circle if needed.

    class RecordingCircle(context: Context, attrs: AttributeSet) : View(context, attrs) {
    
    private val paint: Paint
    private val rect: RectF
    
    private val fillPaint: Paint
    private val fillRect: RectF
    
    var angle: Float
    var startAngle: Float
    
    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RecordingCircle)
        startAngle = typedArray.getFloat(R.styleable.RecordingCircle_startAngle, 0f)
        val offsetAngle = typedArray.getFloat(R.styleable.RecordingCircle_offsetAngle, 0f)
        val color = typedArray.getColor(R.styleable.RecordingCircle_color, ResourcesCompat.getColor(resources, R.color.recording, null))
        val strokeWidth = typedArray.getFloat(R.styleable.RecordingCircle_strokeWidth, 20f)
        val circleSize = typedArray.getDimension(R.styleable.RecordingCircle_cicleSize, 100f)
        val fillColor = typedArray.getColor(R.styleable.RecordingCircle_fillColor, 0)
        typedArray.recycle()
    
        paint = Paint().apply {
            setAntiAlias(true)
            setStyle(Paint.Style.STROKE)
            setStrokeWidth(strokeWidth)
            setColor(color)
        }
    
        rect = RectF(
            strokeWidth,
            strokeWidth,
            (circleSize - strokeWidth),
            (circleSize - strokeWidth)
        )
    
        fillPaint = Paint().apply {
            setAntiAlias(true)
            setStyle(Paint.Style.FILL)
            setColor(fillColor)
        }
    
        val offsetFill = strokeWidth
        fillRect = RectF(
            offsetFill,
            offsetFill,
            (circleSize - offsetFill),
            (circleSize - offsetFill)
        )
    
        //Initial Angle (optional, it can be zero)
        angle = offsetAngle
    }
    
    override protected fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (fillColor > 0) {
            canvas.drawArc(rect, 0f, 360f, false, fillPaint)
        }
        canvas.drawArc(rect, startAngle, angle, false, paint)
    }
    }
    

    And on the xml:

            
    
        
    

    Here the result: Note the semi-transparent fill of the button

提交回复
热议问题