Skip to content

Instantly share code, notes, and snippets.

@acj
Created Oct 6, 2012
Embed
What would you like to do?
Drawing a circumscribed triangle inside a known circle
// This implementation assumes that the origin is at the upper-left corner of the
// drawing surface.
//
// Sample usage:
//
// Paint paint = new Paint();
// paint.setStyle(Paint.Style.STROKE);
// float centerX = 200;
// float centerY = 200;
// float radius = 100;
// canvas.drawCircle(centerX, centerY, radius, paint);
// drawCircumscribedTriangle(canvas, centerX, centerY, radius, (float)Math.PI/4, paint);
class RotateOrderedPair {
float x;
float y;
public RotateOrderedPair(float x, float y, float pivotX, float pivotY, float angle) {
this.x = x;
this.y = y;
if (angle != 0) {
rotateAboutPoint(pivotX, pivotY, angle);
}
}
private void rotateAboutPoint( float pivotX, float pivotY, float angle) {
float newX = FloatMath.cos(angle)*(x - pivotX) - FloatMath.sin(angle)*(y - pivotY) + pivotX;
float newY = FloatMath.sin(angle)*(x - pivotX) + FloatMath.cos(angle)*(y - pivotY) + pivotY;
x = newX;
y = newY;
}
}
private void drawCircumscribedTriangle(Canvas canvas, float circleCenterX, float circleCenterY, float radius, float rotationAngle, Paint paint) {
float xOffsetFromCenter = FloatMath.cos((float)Math.PI/6) * radius;
float yOffsetFromCenter = FloatMath.sin((float)Math.PI/6) * radius;
RotateOrderedPair startA = new RotateOrderedPair(circleCenterX, circleCenterY - radius, circleCenterX, circleCenterY, rotationAngle);
RotateOrderedPair endA = new RotateOrderedPair(circleCenterX + xOffsetFromCenter, circleCenterY + yOffsetFromCenter, circleCenterX, circleCenterY, rotationAngle);
RotateOrderedPair startB = new RotateOrderedPair(circleCenterX + xOffsetFromCenter, circleCenterY + yOffsetFromCenter, circleCenterX, circleCenterY, rotationAngle);
RotateOrderedPair endB = new RotateOrderedPair(circleCenterX - xOffsetFromCenter, circleCenterY + yOffsetFromCenter, circleCenterX, circleCenterY, rotationAngle);
RotateOrderedPair startC = new RotateOrderedPair(circleCenterX - xOffsetFromCenter, circleCenterY + yOffsetFromCenter, circleCenterX, circleCenterY, rotationAngle);
RotateOrderedPair endC = new RotateOrderedPair(circleCenterX, circleCenterY - radius, circleCenterX, circleCenterY, rotationAngle);
canvas.drawLine(startA.x, startA.y, endA.x, endA.y, paint);
canvas.drawLine(startB.x, startB.y, endB.x, endB.y, paint);
canvas.drawLine(startC.x, startC.y, endC.x, endC.y, paint);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment