使用贝塞尔曲线,对坐标进行光滑处理,对于无需进行降噪处理的线条效果较好
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);
// }
}