How to draw filled polygon?

前端 未结 8 2102
生来不讨喜
生来不讨喜 2020-12-01 08:57

How to draw filled polygon in Android ?

8条回答
  •  鱼传尺愫
    2020-12-01 09:20

    This class can be used to draw any kind of polygons. Just call drawPolygonPath() in onDraw() method.

    class PolygonView : View {
        constructor(context: Context?) : super(context) {
            init()
        }
    
        constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
            init()
        }
    
        constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context,
            attrs,
            defStyleAttr
        ) {
            init()
        }
    
        private lateinit var paint: Paint
    
        private fun init() {
            paint = Paint().apply {
                color = Color.RED
                isAntiAlias = true
                style = Paint.Style.FILL
                strokeWidth = 10f
            }
        }
    
    
        override fun onDraw(canvas: Canvas) {
            canvas.drawPath(drawPolygonPath(8, 150f), paint)
            canvas.drawPath(drawPolygonPath(5, 120f), paint)
    
        }
    
        /**
         * @param sides number of polygon sides
         * @param radius side length.
         * @param cx drawing x start point.
         * @param cy drawing y start point.
         * */
        private fun drawPolygonPath(
            sides: Int,
            radius: Float,
            cx: Float = radius,
            cy: Float = radius
        ): Path {
            val path = Path()
            val x0 = cx + (radius * cos(0.0).toFloat())
            val y0 = cy + (radius * sin(0.0).toFloat())
            //2.0 * Math.PI = 2π, which means one circle(360)
            //The polygon total angles of the sides must equal 360 degree.
            val angle = 2 * Math.PI / sides
    
            path.moveTo(x0, y0)
    
            for (s in 1 until sides) {
    
                path.lineTo(
                    cx + (radius * cos(angle * s)).toFloat(),
                    cy + (radius * sin(angle * s)).toFloat()
                )
            }
    
            path.close()
    
            return path
        }
    }
    

提交回复
热议问题