I need to draw polygons like triangle, trapezoid, pentagon, parallelogram, rhombus etc. It seems Path class is way to go, however i need these polygons have rounded corners and i also need to control the amount of the rounding.
In Android, we can easily draw objects using the Canvas function. In the case of a complex object, we can create a path and load this path in the canvas for creating the object. To add customized effects, such as rounded corners, we can add path effects inside the canvas.
If you want a rectangle with rounded corners, use drawRoundedRect. It’s similar to drawRect but with the addition of radiusX and radiusY to define the curvature of the rounded corners. It draws an evenly rounded corner if radiusX equals radiusY.
A regular polygon, such as a pentagon, can be drawn inside the unit circle as follows: In order to draw the pentagon we need to be able to identify the 5 points on the unit circle and rotate and draw lines between them. This is where some understanding of trigonometry comes in useful. Let's consider some point, (a, b) on the unit circle as follows:
If you want a rectangle with rounded corners, use drawRoundedRect. It’s similar to drawRect but with the addition of radiusX and radiusY to define the curvature of the rounded corners. It draws an evenly rounded corner if radiusX equals radiusY. When radiusX = radiusY, it will have the usual rounded corners as below:
Find below a simple example to draw rounded corner polygons (i.e. triangle, rectangle, etc.)
@Override public void draw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.GREEN); paint.setStrokeWidth(6); float radius = 50.0f; CornerPathEffect corEffect = new CornerPathEffect(radius); paint.setPathEffect(corEffect); Path path = new Path(); path.moveTo(20, 20); path.lineTo(400, 20); path.lineTo(600, 300); path.lineTo(400, 400); path.lineTo(20, 400); path.close(); canvas.drawPath(path, paint); }
In order to control the amount of rounding, change the value of radius.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With