今日项目中遇到一个需要单点旋转2D元素的问题,利用向量将问题解决了。
首先在鼠标Down下时记录起始点m_orDownPoint,鼠标Move时根据当前鼠标点形成的向量与上次记录m_orDownPoint形成的向量来计算夹角。
代码如下:
void CGraphicElementBaseClass::ChangeRotationByEditBox(const TOUCHINPUT* inData)
{
//计算元素中心点
D2D1_POINT_2F center = D2D1::Point2F((m_fXR + m_fWidth/2.0f),(m_fYR + m_fHeight/2.0f));
//计算m_orDownPoint到中心点的向量U
FLOAT Ux = m_orDownPoint.x - center.x;
FLOAT Uy = m_orDownPoint.y - center.y;
//计算inData到中心点的向量V
FLOAT Vx = inData->x - center.x;
FLOAT Vy = inData->y - center.y;
//计算向量的模
FLOAT moduleU = sqrtf(Ux*Ux + Uy*Uy);
FLOAT moduleV = sqrtf(Vx*Vx + Vy*Vy);
if((moduleU) < 0.00001f || (moduleV) < 0.00001f)
return;
//根据向量叉积求夹角
FLOAT angle = asinf((Ux*Vy - Vx*Uy) / (moduleU* moduleV));
FLOAT Angle = angle* 180.0f/PI;