Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Canvas - drawing an equilateral triangle
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(sideLength: Float, path: Path): Path {
// pointing up
path.moveTo(0f, sideLength)
path.lineTo(sideLength / 2f, sideLength - getHeight(sideLength.toDouble()))
path.lineTo(sideLength, sideLength)
// pointing down
// path.lineTo((sideLength / 2f), getHeight(sideLength.toDouble()))
// path.lineTo(sideLength, 0f)
// path.lineTo(0f, 0f)
// pointing right
// path.lineTo(0f, 0f)
// path.lineTo(0f, sideLength)
// path.lineTo(getHeight(sideLength.toDouble()), (sideLength / 2f))
// pointing left
// path.moveTo(sideLength, 0f)
// path.lineTo(sideLength, sideLength)
// path.lineTo(sideLength - getHeight(sideLength.toDouble()), sideLength / 2f)
return path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment