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

前端 未结 3 1968
眼角桃花
眼角桃花 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:26

    Added code for calculating correct circle measurements

    import android.content.Context
    import android.graphics.Canvas
    import android.graphics.Color
    import android.graphics.Paint
    import android.graphics.RectF
    import android.util.AttributeSet
    import android.view.View
    import androidx.core.content.ContextCompat
    
    class Circle(context: Context, attrs: AttributeSet) : View(context, attrs) {
    
        private val paint: Paint
        private val rect: RectF
    
        var angle = 0f
    
        companion object {
            private val START_ANGLE_POINT = 270f
        }
    
        init {
            val strokeWidth = resources.getDimension(R.dimen.toast_circle_stroke_width)
    
            paint = Paint().apply {
                setAntiAlias(true)
                setStyle(Paint.Style.STROKE)
                setStrokeWidth(strokeWidth)
                setColor(Color.RED)
            }
    
            val circleSize = resources.getDimension(R.dimen.toast_circle_size)
    
            rect = RectF(
                strokeWidth,
                strokeWidth,
                circleSize + strokeWidth,
                circleSize + strokeWidth
            )
        }
    
        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
            val circleSize = resources.getDimension(R.dimen.toast_circle_size).toInt()
            val strokeWidth = resources.getDimension(R.dimen.toast_circle_stroke_width).toInt()
    
            super.onMeasure(
                MeasureSpec.makeMeasureSpec(circleSize + 2 * strokeWidth, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(circleSize + 2 * strokeWidth, MeasureSpec.EXACTLY));
        }
    
        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            canvas.drawArc(rect, START_ANGLE_POINT, angle, false, paint)
        }
    
    }
    

提交回复
热议问题