Qt:繪畫箭頭線段

基本數學原理

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.
Qt:繪畫箭頭線段 - 柳北風兒 - 柳北風兒~~~~~~~欲宇仙炅
 
 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_);
}


Qt:繪畫箭頭線段 - 柳北風兒 - 柳北風兒~~~~~~~欲宇仙炅

原文地址:http://blog.163.com/qimo601@126/blog/static/15822093201631753937614/?suggestedreading&wumii
發佈了2 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章