本来打算用绘制贝塞尔曲线的方法绘制心形,可是本数学渣怎么都搞不定那几个控制点坐标。研究了一上午,通过lineTo方法,最终还是绘制出封闭的心形图。还收获了意外的效果。
看来就差个女朋友,给她看了。
代码如下:
.h文件
1 #pragma once 2 3 #include <QtWidgets/QDialog> 4 #include "ui_heart.h" 5 #include <Qpainter> 6 class Heart : public QDialog 7 { 8 Q_OBJECT 9 public: 10 Heart(QWidget *parent = Q_NULLPTR); 11 protected: 12 void paintEvent(QPaintEvent *); 13 private: 14 Ui::HeartClass ui; 15 };
.cpp文件
1 #include "heart.h" 2 3 Heart::Heart(QWidget *parent): QDialog(parent) 4 { 5 ui.setupUi(this); 6 } 7 8 void Heart::paintEvent(QPaintEvent *event) 9 { 10 double k = 10; 11 QPainter painter(this); 12 painter.setRenderHint(QPainter::Antialiasing, true); 13 QColor my_color(237, 162, 255, 255); 14 QBrush my_brush(my_color); 15 painter.setPen(Qt::red); 16 /*painter.setBrush(my_brush);*/ 17 painter.translate(this->width()/2, this->height()/2); 18 QPainterPath polygonPath; 19 polygonPath.setFillRule(Qt::WindingFill); 20 float x = 16 * k * sin(0.0)*sin(0.0)*sin(0.0); 21 float y = 13 * k * cos(0.0) - 5 * k*cos(0.0) - 2 * k*cos(0.0) - cos(0.0); 22 polygonPath.moveTo(x, -y); 23 for (double t = 0.01; t < 100; t += 0.05) 24 { 25 x = 16 * k * sin(k*t)*sin(k*t)*sin(k*t); 26 y = 13 * k * cos(k*t) - 5 * k * cos(2 * k * t) - 2 * k * cos(3 * k * t) - cos(4 * k * t); 27 polygonPath.lineTo(x, -y); 28 /*painter.drawPoint(x,-y); 29 painter.drawLine(0,0,x,-y); 30 painter.drawLine(0,0,x+100,-y);*/ 31 } 32 painter.drawPath(polygonPath); 33 }