我在画布上画了一个三角形:
float x = 540;
float y = 960;
Path path = new Path();
path.moveTo(x, y);
path.lineTo(x+18, y+60);
path.lineTo(x-18, y+60);
path.lineTo(x, y);
canvas.drawPath(path, mPaint);
此画布有另一个对象。但是我需要在一个随机角度(0到360之间)围绕这个三角形的中心旋转这个三角形。怎么实现呢?如何在旋转后获得三角形的坐标顶点?
答案 0 :(得分:2)
它的简单数学,如果三角形的中心是(x,y)而中心顶点的距离是A,则三个顶点将是
- (A * Math.cos(角),A * Math.sin(角度))
- (A * Math.cos(角度+ 2 * Math.PI / 3),A * Math.sin(角度+ 2 * Math.PI / 3))
- (A * Math.cos(角度-2 * Math.PI / 3),A * Math.sin(角度-2 * Math.PI / 3))
答案 1 :(得分:0)
我通过这种方式解决它:
float angle = (float) Math.toRadians(90); // Angle to rotate
// Size of triangle
final float height = 60;
final float width = 36;
// Display coordinates where triangle will be drawn
float centerX = 540;
float centerY = 960;
// Vertex's coordinates before rotating
float x1 = centerX;
float y1 = centerY - height / 2;
float x2 = centerX + width / 2;
float y2 = centerY + height / 2;
float x3 = centerX - width / 2;
float y3 = y2;
// Rotating
float x1r = (float) ((x1 - centerX) * Math.cos(angle) - (y1 - centerY) * Math.sin(angle) + centerX);
float y1r = (float) ((x1 - centerX) * Math.sin(angle) + (y1 - centerY) * Math.cos(angle) + centerY);
float x2r = (float) ((x2 - centerX) * Math.cos(angle) - (y2 - centerY) * Math.sin(angle) + centerX);
float y2r = (float) ((x2 - centerX) * Math.sin(angle) + (y2 - centerY) * Math.cos(angle) + centerY);
float x3r = (float) ((x3 - centerX) * Math.cos(angle) - (y3 - centerY) * Math.sin(angle) + centerX);
float y3r = (float) ((x3 - centerX) * Math.sin(angle) + (y3 - centerY) * Math.cos(angle) + centerY);
// Drawing
Path path = new Path();
path.moveTo(x1r, y1r);
path.lineTo(x2r, y2r);
path.lineTo(x3r, y3r);
path.lineTo(x1r, y1r);
canvas.drawPath(path, mPaint);
感谢Gimka和Nofate的帮助。