How to draw filled polygon?

Viewed 80730

How to draw filled polygon in Android ?

8 Answers

You need to set the paint object to FILL

Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);

Then you can draw whatever you want, and it will be filled.

canvas.drawCircle(20, 20, 15, paint);
canvas.drawRectangle(60, 20, 15, paint);

etc.

For more complex shapes you need to use the PATH object.

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
    }
}
Related