基本数学原理
Basics
With the function
atan2
we can obtain the angle of the source line. Adding to this angle a defined sub-angle (arrow_degrees_) we can get the left and right angle of the arrow arms. With this two angles and using a defined lenght for the arrow arms (arrow_lenght_) we can finally achieve two points to use for perform drawing operations.
Now return to the future...we need to transform this on c++ code.
void calcVertexes(double start_x, double start_y, double end_x, double end_y, double& x1, double& y1, double& x2, double& y2) { double angle = atan2 (end_y - start_y, end_x - start_x) + M_PI; x1 = end_x + arrow_lenght_ * cos(angle - arrow_degrees_); y1 = end_y + arrow_lenght_ * sin(angle - arrow_degrees_); x2 = end_x + arrow_lenght_ * cos(angle + arrow_degrees_); y2 = end_y + arrow_lenght_ * sin(angle + arrow_degrees_); }
Qt源码如下三段:
void Test::paintEvent(QPaintEvent* event)
{
drawArrow();
}
void Test::drawArrow()
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin));
QPointF startPoint(5,5);
QPointF endPoint(100,200);
double x1, y1, x2, y2; //箭头的两点坐标
//求得箭头两点坐标
calcVertexes(startPoint.x(), startPoint.y(), endPoint.x(), endPoint.y(), x1, y1, x2, y2);
painter.drawLine(startPoint, endPoint);//绘制线段
painter.drawLine(endPoint.x(), endPoint.y(), x1, y1);//绘制箭头一半
painter.drawLine(endPoint.x(), endPoint.y(), x2, y2);//绘制箭头另一半
}
//求箭头两点坐标
void Test::calcVertexes(double start_x, double start_y, double end_x, double end_y, double& x1, double& y1, double& x2, double& y2)
{
double arrow_lenght_ = 10;//箭头长度,一般固定
double arrow_degrees_ = 0.5;//箭头角度,一般固定
double angle = atan2(end_y - start_y, end_x - start_x) + 3.1415926;//
x1 = end_x + arrow_lenght_ * cos(angle - arrow_degrees_);//求得箭头点1坐标
y1 = end_y + arrow_lenght_ * sin(angle - arrow_degrees_);
x2 = end_x + arrow_lenght_ * cos(angle + arrow_degrees_);//求得箭头点2坐标
y2 = end_y + arrow_lenght_ * sin(angle + arrow_degrees_);
}
原文地址:http://blog.163.com/qimo601@126/blog/static/15822093201631753937614/?suggestedreading&wumii