正常情况下,用 QPainter 的drawPixmap只能显示距形的图片。如果我们想显示带圆角的,甚至要求比如 只要左上角和右上角带圆角的图片呢。我们可以采用QPainterPath先画出我们想要形状,再加载图片显示出来。不废话,看代码。
#define TOP_LEFT_CORNER 1 //左上角
#define TOP_RIGHT_CORNER 2 //右上角
#define BOTTOM_RIGHT_CORNER 4 //右下角
#define BOTTOM_LEFT_CORNER 8 //左下角
QPainterPath makeAnyRoundedRect(const QRect& rect,int radius,int corner)//返回一个path
{ //rect 距形
//参数 radius 圆角距形半径
//corner 取上面4个值的任意组合。表示那个要圆角。
QPainterPath path;
if(corner & TOP_LEFT_CORNER)
{
path.moveTo(rect.x() + radius,rect.y());
path.arcTo(rect.x(),rect.y(),radius*2,radius*2,90.f,90.f);//画左上圆角
}
else
{
path.moveTo(rect.x(),rect.y());
}
if(corner & BOTTOM_LEFT_CORNER)
{
path.lineTo(rect.x(),rect.y() + rect.height() -radius);
path.arcTo(rect.x(),rect.y() + rect.height() - radius *2,radius*2,radius*2,180.0f,90.f);
}
else
{
path.lineTo(rect.x(),rect.y() + rect.width());
}
if(corner & BOTTOM_RIGHT_CORNER)
{
path.lineTo(rect.x() + rect.width() - radius,rect.y() + rect.height());
path.arcTo(rect.x() + rect.width() - 2*radius,rect.y() + rect.height() - 2*radius,radius*2,radius*2,270.0f,90.f);
}
else
{
path.lineTo(rect.x()+ rect.width(),rect.y() + rect.height());
}
if(corner & TOP_RIGHT_CORNER)
{
path.lineTo(rect.x() + rect.width(),rect.y() + radius);
path.arcTo(rect.x() + rect.width() - 2*radius,rect.y(),radius*2,radius*2,0.f,90.f);
}
else
{
path.lineTo(rect.x()+ rect.width(),rect.y());
}
return path;
}
//调用方法
void Widget::paintEvent(QPaintEvent *event)
{
QRect rect(30, 30, 200, 200);
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing); //抗锯齿
int border_radius = 10;//圆角半径
auto picPath = makeAnyRoundedRect(rect,border_radius,TOP_RIGHT_CORNER | BOTTOM_LEFT_CORNER);
p.setClipPath(picPath);
QPixmap pic;
pic.load("newest.jpeg");
p.drawPixmap(rect,pic);
}
下面是实际效果