Created
June 29, 2017 05:22
-
-
Save jwmaher/b3eb8bdea186a8cf38aa3e26f6fea3fc to your computer and use it in GitHub Desktop.
Android Canvas - drawing an equilateral triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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