QT5实现光滑曲线

使用贝塞尔曲线,对坐标进行光滑处理,对于无需进行降噪处理的线条效果较好
SmoothCurveGenerator.h

#include <QList>
#include <QPainterPath>
class SmoothCurveGenerator{
public:
    static QPainterPath generateSmoothCurve(QList<QPointF> points, bool closed = false, double tension = 0.5, int numberOfSefments = 16);
    static QPainterPath generateSmoothCurve(QList<double>points, bool closed = false, double tension = 0.5, int numberOfSegments = 16);
//points是坐标,closed是是否封闭,tension是密集程度,Numberofsegment是两个端点间的线段数
    static QPainterPath DrawcommonLine(QList<QPointF> points);
};
#endif // SMOOTHCURVEGENERATOR_H

SmoothCurveGenerator.c

#include <QList>
#include <QPainterPath>
class SmoothCurveGenerator{
public:
    static QPainterPath generateSmoothCurve(QList<QPointF> points, bool closed = false, double tension = 0.5, int numberOfSefments = 16);
    static QPainterPath generateSmoothCurve(QList<double>points, bool closed = false, double tension = 0.5, int numberOfSegments = 16);
//points是坐标,closed是是否封闭,tension是密集程度,Numberofsegment是两个端点间的线段数
    static QPainterPath DrawcommonLine(QList<QPointF> points);
};
#endif // SMOOTHCURVEGENERATOR_H

制作一个例程
Form.h

#ifndef FORM_H
#define FORM_H
#include <QWidget>
#include <QList>
#include <QPainterPath>

class Form:public QWidget{
Q_OBJECT
public:
    explicit Form(QWidget*parent=0);
    ~Form();
protected:
    void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
private:
    QList<QPointF> points1;
    QList<QPointF> points2;
    QPainterPath smoothCurvePath;
    QPainterPath commonCurvePath;
};
#endif // FORM_H

Form.c

#include "Form.h"
#include "SmoothCurveGenerator.h"

#include <QDebug>
#include <QPainter>
#include <QDateTime>
Form::Form(QWidget *parent):QWidget(parent){

    qsrand(QDateTime::currentDateTime().toTime_t());
    // 随机生成曲线第一条曲线的坐标
    int x = 0, y = 0;
    int gpsnum=0;
    for (int i = 0; i < 100; ++i) {

    x += qrand() % 32 + 10;
    y = qrand() % 181 + 50;
    points1 << QPointF(x, y);
    }

    // 使用曲线的坐标生成平滑曲线
    smoothCurvePath = SmoothCurveGenerator::generateSmoothCurve(points1); // 生成曲线
    //commonCurvePath = SmoothCurveGenerator::DrawcommonLine(points1);
    }

    Form::~Form() {
    }

    void Form::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(QPen(Qt::black, 2));


    // 绘制平滑曲线
    painter.drawPath(smoothCurvePath);
//    painter.drawPath(commonCurvePath);

    //绘制曲线上的顶点
//    painter.setBrush(Qt::gray);
//    for (int i = 0; i < points1.length() ; i += 1) {
//    painter.drawEllipse(points1[i].x()-3, points1[i].y()-3, 6, 6);
//    }

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值