31.paint渐变色绘图--Apple的学习笔记
2021-08-28 本文已影响0人
applecai
一,前言
看到别人做的比较好玩的应用中,有些对象要自己绘图的。所以渐变色绘图基础我先学习下。
二,需求
绘制线性渐变,圆形角度渐变及辐射渐变。
三,API用法小结
- 笔刷的渐变填充类型
QLinearGradient:显示从起点到终点的渐变
QRadialGradient:以圆心为中心显示渐变
QConicalGradient:角度渐变,需要转换坐标系 - 笔刷的渐变方式
QGradient::PadSpread:顺序填充
QGradient::RepeatSpread:重复填充
QGradient::ReflectSpread:镜像填充
四,源码
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
// 反走样
painter.setRenderHint(QPainter::Antialiasing, true);
// 设置渐变色
//QLinearGradient linear(QPointF(100, 100), QPointF(100, 150));
QLinearGradient linear(QPointF(100, 100), QPointF(150, 150));
linear.setColorAt(0, Qt::red);
linear.setColorAt(1, Qt::white);
// 设置显示模式
linear.setSpread(QGradient::RepeatSpread);
// 设置画笔颜色、宽度
painter.setPen(QPen(QColor(38, 0, 210), 2));
// 设置画刷填充
painter.setBrush(linear);
// 绘制左边矩形
painter.drawRect(QRect(10, 10, 200, 200));
// 绘制右边矩形
QPainter painter2(this);
QLinearGradient linear2;
linear2.setStart(QPointF(100, 100));
linear2.setFinalStop(QPointF(150, 150));
linear2.setSpread(QGradient::ReflectSpread);
linear2.setColorAt(0, Qt::blue);
linear2.setColorAt(1, Qt::white);
painter2.setBrush(linear2);
painter2.setPen(QPen(QColor(38, 0, 210), 2));
painter2.drawRect(QRect(220, 10, 200, 200));
// 画圆
QPainter painter3(this);
painter3.setRenderHint(QPainter::Antialiasing);
const int r =100;
// 中心点+起始角度
QConicalGradient conicalGradient(0, 0, 0);
conicalGradient.setColorAt(0.0, Qt::red);
conicalGradient.setColorAt(60.0/360.0, Qt::yellow);
conicalGradient.setColorAt(120.0/360.0, Qt::green);
conicalGradient.setColorAt(180.0/360.0, Qt::cyan);
conicalGradient.setColorAt(240.0/360.0, Qt::blue);
conicalGradient.setColorAt(300.0/360.0, Qt::magenta);
conicalGradient.setColorAt(1.0, Qt::red);
// 绘图坐标系转换
painter3.translate(110, 320);
QBrush brush(conicalGradient);
painter3.setPen(Qt::NoPen);
painter3.setBrush(brush);
painter3.drawEllipse(QPoint(0, 0), r, r);
QPainter painter4(this);
painter4.setRenderHint(QPainter::Antialiasing,true);
painter4.translate(320,320);
//原点+半径100+焦点为0,0
QRadialGradient Radial(0,0,100,0,0);
Radial.setColorAt(0,Qt::white);
Radial.setColorAt(0.4,Qt::red);
Radial.setColorAt(0.8,Qt::darkRed);
Radial.setColorAt(1,Qt::gray);
painter4.setPen(Qt::transparent);
painter4.setBrush(Radial);
painter4.drawEllipse(QPoint(0, 0),r,r);
}
五,效果
image.png六,小结
QT里面最好玩的还是绘图,哈哈~