How to draw filled polygon?

Android does not have a handy drawPolygon(x_array, y_array, numberofpoints) action like Java. You have to walk through making a Path object point by point. For example, to make a filled trapezoid shape for a 3D dungeon wall, you could put all your points in x and y arrays then code as follows:

Paint wallpaint = new Paint();
wallpaint.setColor(Color.GRAY);
wallpaint.setStyle(Style.FILL);

Path wallpath = new Path();
wallpath.reset(); // only needed when reusing this path for a new build
wallpath.moveTo(x[0], y[0]); // used for first point
wallpath.lineTo(x[1], y[1]);
wallpath.lineTo(x[2], y[2]);
wallpath.lineTo(x[3], y[3]);
wallpath.lineTo(x[0], y[0]); // there is a setLastPoint action but i found it not to work as expected

canvas.drawPath(wallpath, wallpaint);

To add a constant linear gradient for some depth, you could code as follows. Note y[0] is used twice to keep the gradient horizontal:

 wallPaint.reset(); // precaution when resusing Paint object, here shader replaces solid GRAY anyway
 wallPaint.setShader(new LinearGradient(x[0], y[0], x[1], y[0], Color.GRAY, Color.DKGRAY,TileMode.CLAMP)); 

 canvas.drawPath(wallpath, wallpaint);

Refer to Paint, Path and Canvas documentation for more options, such as array defined gradients, adding arcs, and laying a Bitmap over your polygon.

Leave a Comment