如何画心形在往期(20200520期《简单画心形》)推送中有介绍到,但它不能随着窗口大小变化而变化,还不够好,所以加上这个小功能,分享给大家。
自绘画心形
代码语言:javascript复制/* 当窗口大小发生变化时,触发重绘事件。 */
void resizeEvent(QResizeEvent *)
{
update();
}
/* 画心形 */
void paintEvent(QPaintEvent *)
{
float scale = 1;
if (width() > height()) {
scale = height()/28.9233;
}
else {
scale = width()/32.0;
}
QPainter painter(this);
painter.translate(width()/2, (height() - scale * 5.0767)/2);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(Qt::red));
QVector<QPointF> lines;
for (float t = 0; t < 2 * M_PI; t = 0.001) {
float x = 16 * pow(sinf(t), 3); // -16 <= x <= 16
float y = 13 * cosf(t) - 5 * cosf(2 *t) - 2 * cosf(3 * t) - cosf(4 * t); // -17 <= y <= 11.9233
lines.append(QPointF(x*scale, -y*scale));
}
painter.drawPolygon(lines);
}