Qt 绘图渐变填充
2019-08-09 本文已影响0人
飞扬code
渐变填充
QGradient 可以和 QBrush 组合使用,来指定渐变填充。
Qt 目前支持三种类型的渐变填充:

1、QLinearGradient:显示从起点到终点的渐变

2、QRadialGradient:以圆心为中心显示渐变

3、QConicalGradient:围绕一个中心点显示渐变

渐变类型可以使用 type() 函数来检索,类型中的每一个都是 QGradient 的子类。
QLinearGradient
QPainter painter(this);
// 反走样 painter.setRenderHint(QPainter::Antialiasing, true);
// 设置渐变色
QLinearGradient linear(QPointF(80, 80), QPointF(150, 150));
linear.setColorAt(0, Qt::black);
linear.setColorAt(1, Qt::white);
// 设置显示模式
//QGradient::PadSpread 使用最接近的颜色进行填充(....y, y, r, g, g....)
//QGradient::ReflectSpread 在渐变区域以外的区域反射渐变(y, r, g, g, r, y)
//QGradient::RepeatSpread 在渐变区域以外的区域重复渐变(y, r, g, y, r, g)
linear.setSpread(QGradient::PadSpread);
// 设置画笔颜色、宽度
painter.setPen(QPen(QColor(0, 160, 230), 2));
// 设置画刷填充
painter.setBrush(linear);
// 绘制椭圆
painter.drawRect(QRect(40, 40, 180, 180));
效果:

QLinearGradient 构造函数的第一个参数指定起点,第二个参数指定终点,然后显示渐变。函数setColorAt() 用于设置起点和终点之间要显示的颜色,setSpread() 可以设置起点和终点区域之外的显示模式。
QRadialGradient
QRadialGradient 类以圆心为中心显示渐变。(cx, cy) 是中点,半径(radius)是以中点为圆心的圆的半径,(fx, fy) 是渐变的起点。
QPainter painter(this);
// 反走样
painter.setRenderHint(QPainter::Antialiasing, true);
// 设置渐变色
QRadialGradient radial(110, 110, 50, 130, 130);
radial.setColorAt(0, Qt::black);
radial.setColorAt(1, Qt::white);
// 设置显示模式
radial.setSpread(QGradient::ReflectSpread );
// 设置画笔颜色、宽度
painter.setPen(QPen(QColor(0, 160, 230), 2));
// 设置画刷填充
painter.setBrush(radial);
// 绘制椭圆
painter.drawRect(QRect(40, 40, 180, 180));
效果:

QRadialGradient 构造函数的第一个参数和第二个参数是 (cx, cy) 坐标,第三个参数是半径,第四个和第五个参数是 (fx, fy) 坐标。
QConicalGradient
QConicalGradient 在 (cx, cy) 坐标上以角度 (angle) 为中心显示渐变。
QPainter painter(this);
// 反走样
painter.setRenderHint(QPainter::Antialiasing, true);
// 设置渐变色
QConicalGradient conical(110, 110, 45);
conical.setColorAt(0, Qt::black);
conical.setColorAt(1, Qt::white);
// 设置画笔颜色、宽度
painter.setPen(QPen(QColor(0, 160, 230), 2));
// 设置画刷填充
painter.setBrush(conical);
// 绘制椭圆
painter.drawRect(QRect(40, 40, 180, 180));
效果:
