I have class MyView that extends View class. MyView should draw filled triangle. I drew a triangle but I cannot get it filled. This is my onDraw() method:
@O
This answer provides a bit of clarity on where the numbers given in the answer by @Egis come from. (this will draw an upside down equilateral triangle and is written in kotlin)
class TriangleView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
val paint = Paint()
val path = Path()
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas ?: return
canvas.drawPath(configurePath(canvas.width.toFloat(), path), configurePaint(paint))
}
fun getHeight(width: Double): Float {
return Math.sqrt((Math.pow(width, 2.0) - Math.pow((width / 2), 2.0))).toFloat()
}
fun configurePaint(paint: Paint): Paint {
paint.color = android.graphics.Color.WHITE
paint.isAntiAlias = true
return paint
}
fun configurePath(width: Float, path: Path): Path {
path.lineTo((width / 2f), getHeight(width.toDouble()))
path.lineTo(width, 0F)
path.lineTo(0f, 0f)
return path
}
}
The get height function is Pythagoras' Theorem and will always find the height of an equilateral triangle to be ~87% of its side length
Gist can be found here, it contains code for the other direction