❝使用QPainter画甜甜圈。❞
1. 实现
- 将甜甜圈绘制在
QPixmap
中,最后再绘制在窗口中。 - 甜甜圈使用
QLinearGradient
实现渐变效果。 - 设置画笔的宽度实现甜甜圈的宽度。
- 最后使用
drawEllipse
方法画圆。
2. 核心代码
- 绘制单个甜甜圈代码。
QPixmap Donut::createOneDount(int radius, int width, const QColor &color)
{
QPixmap pixmap = QPixmap(radius, radius);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
QLinearGradient linearGradient(0, 0, radius, radius);
linearGradient.setColorAt(0.0, color.light());
linearGradient.setColorAt(0.8, color);
linearGradient.setColorAt(1.0, color.dark());
painter.setPen(QPen(QBrush(linearGradient), width));
painter.translate(painter.pen().width()/2, painter.pen().width()/2);
painter.drawEllipse(0,
0,
radius - painter.pen().width(),
radius - painter.pen().width());
return pixmap;
}
- 绘制一堆甜甜圈实现代码。
void Donut::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
const QString colors[3][3] = {
{"#F9C46E", "#B6AFEA", "#402B0A"},
{"#DEAB9E", "#ADD475", "#BF593E"},
{"#6ABEEA", "#B97D1C", "#D5E9B9"},
};
for (int i = 0; i < 4; i ) {
for (int j = 0; j < 5; j ) {
painter.drawPixmap(qrand()%width(),
qrand()%height(),
createOneDount(200, 70, QColor(colors[j%3][i%3])));
}
}
}