输入图形A的中点坐标(2,2)
在图形B中应该是(8,2)
#include <stdio.h>
#include <math.h>
typedef struct {
float x;
float y;
} Point;
float dotProduct(Point p1, Point p2) {
return p1.x * p2.x + p1.y * p2.y;
}
int isPointInRectangle(Point p, Point A, Point B, Point C, Point D) {
Point AB = { B.x - A.x, B.y - A.y };
Point BC = { C.x - B.x, C.y - B.y };
Point CD = { D.x - C.x, D.y - C.y };
Point DA = { A.x - D.x, A.y - D.y };
Point AP = { p.x - A.x, p.y - A.y };
Point BP = { p.x - B.x, p.y - B.y };
Point CP = { p.x - C.x, p.y - C.y };
Point DP = { p.x - D.x, p.y - D.y };
return dotProduct(AB, AP) >= 0 && dotProduct(BC, BP) >= 0 &&
dotProduct(CD, CP) >= 0 && dotProduct(DA, DP) >= 0;
}
Point mapPoint(Point p, Point A[], Point B[]) {
Point A1 = A[0];
Point B1 = B[0];
Point A2 = A[2];
Point B2 = B[2];
// 计算矩形1的旋转角度
float theta = atan2(A2.y - A1.y, A2.x - A1.x);
// 计算矩形2的旋转角度
float phi = atan2(B2.y - B1.y, B2.x - B1.x);
// 计算总旋转角度
float totalRotation = phi - theta;
// 计算映射点相对于矩形1左上角的坐标
float translatedX = p.x - A1.x;
float translatedY = p.y - A1.y;
// 应用旋转变换
float rotatedX = translatedX * cos(totalRotation) - translatedY * sin(totalRotation);
float rotatedY = translatedX * sin(totalRotation) + translatedY * cos(totalRotation);
// 计算矩形2的缩放比例
float scaleX = hypot(B2.x - B1.x, B2.y - B1.y) / hypot(A2.x - A1.x, A2.y - A1.y);
float scaleY = hypot(B2.x - B1.x, B2.y - B1.y) / hypot(A2.x - A1.x, A2.y - A1.y);
// 应用缩放变换
rotatedX *= scaleX;
rotatedY *= scaleY;
// 计算映射点相对于矩形2左上角的坐标
float finalX = B1.x + rotatedX;
float finalY = B1.y + rotatedY;
Point mappedPoint;
mappedPoint.x = finalX;
mappedPoint.y = finalY;
return mappedPoint;
}
int main() {
Point A1 = { 0, 0 };
Point A2 = { 0, 4 };
Point A3 = { 4, 4 };
Point A4 = { 4, 0 };
//Point B1 = { 0, 0 };
//Point B2 = { sqrt(18), sqrt(18) };
//Point B3 = { 2*sqrt(18), 0 };
//Point B4 = { sqrt(18), -sqrt(18) };
Point B1 = { 8, 0 };
Point B2 = { 6, 2 };
Point B3 = { 8, 4 };
Point B4 = { 10, 2 };
Point A[4] = { A1, A2, A3, A4 };
Point B[4] = { B1, B2, B3, B4 };
Point p;
printf("请输入检测点的坐标 (x y): ");
scanf("%f %f", &p.x, &p.y);
if (isPointInRectangle(p, A1, A2, A3, A4)) {
Point mappedPoint = mapPoint(p, A, B);
printf("映射后的坐标:(%f, %f)\n", mappedPoint.x, mappedPoint.y);
}
else {
printf("点不在矩形1内部。\n");
}
return 0;
}
结果正确,但是没有只是验证了中点是正确的感觉说服力度不够,图形也没有啥其他特殊点能验证。目前也一个图形中只有中点我们可以人为计算出他映射后的结果,然后代码验证。