学习了QPainter基础绘制后,接下来,来学习QPainter其它函数之rotate()函数
首先来看看QPainter其它函数
void QPainter::drawPixmap ( int x, int y, int w, int h,const QPixmap & pixmap, int sx, int sy, int sw, int sh );//绘画pixmap// x y w h:表示本身的绘画面积//sx sy sw sh:表示pixmap的绘画面积void QPainter::drawPixmap ( int x, int y, const QPixmap & pixmap, int sx, int sy, int sw, int sh );//绘画pixmap// x y 表示绘画起始位置//sx sy sw sh:表示pixmap的绘画面积drawTiledPixmap ( int x, int y, int width, int height, const QPixmap & pixmap,int sx = 0, int sy = 0 );//平铺pixmapvoid QPainter::translate ( qreal dx, qreal dy );//将坐标(dx,dy)设置显示原点void scale ( qreal sx, qreal sy )//设置图片缩放,sx(横坐标放大系数),sy(纵坐标放大系数)void rotate ( qreal angle ); //旋转绘画区域(比如斜文本),angle=90,则表示90度//以时针方向旋转(顺时针)
rotate()函数分析
(资料图片)
如果没有通过translate()设置中心原点,则默认将图片以(0,该图片的高)为原点
示例1-未设置原点中心时
QPainter painter(this);for(int i=0;i<10;i++){painter.save();painter.rotate(i*10);painter.drawText(100,100,\"123\");painter.restore();}
如上图,可以看到原点位于窗口最左侧. ,并且高度等于最右边位置
示例2-设置原点中心后
static int rotate = 0;QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing,true);painter.translate(width()/2,height()/2);painter.drawRect(-2,-2,4,4);painter.setFont(QFont(0,11));for(int i=0;i<10;i++){painter.save();painter.rotate(i*36);painter.drawText(100,0,20,20,Qt::AlignCenter,QString(\"%1\").arg(i));painter.restore();}
效果:
从上图可以看到旋转的同时,文字也跟着倾斜了,接下来,我们来自己写个rotate()函数,不让文字倾斜
示例3-文字不倾斜旋转
/* point: 文字所在的点* from_angle : 文字所在的度数* rotate : 需要旋转的角度,值为-360~360(为负数表示逆时针旋转,为正数表示顺时针旋转)*/QPoint Widget::CustomRotate(QPointF point,qreal from_angle,qreal rotate){qreal PI=3.141592653589;QPointF Tmp;qreal arc = (rotate-from_angle)/180*PI;qreal Length = qSqrt(point.x()*point.x() +point.y()*point.y());Tmp.setX(Length*qCos(arc));Tmp.setY(Length*qSin(arc));return Tmp.toPoint();}void Widget::paintEvent(QPaintEvent *){int angle = 0;QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing,true);painter.translate(width()/2,height()/2);painter.drawRect(-2,-2,4,4);painter.setFont(QFont(0,11));QPoint point(100,0); //从(100,0)开始填文字for(int i=0;i<10;i++){painter.drawText(point.x()-10,point.y()-10,20,20,Qt::AlignCenter,QString(\"%1\").arg(i));point=CustomRotate(point,angle, 36); //以当前angle度,顺时针旋转36度angle -=36; //更新度数,由于顺时针,所以用减}}
效果:
示例4-通过选择加载图片实现等待效果
代码如下:
Widget::Widget(QWidget *parent) :QWidget(parent),m_rotate(false){resize(300,300);connect(&timer,SIGNAL(timeout()),this,SLOT(timerout()));timer.start(40);}void Widget::timerout(){m_rotate =true;update();}void Widget::paintEvent(QPaintEvent *){static int rotate = 0;QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing,true);painter.translate(width()/2,height()/2);if(m_rotate){rotate = (rotate+5)%360;m_rotate =false;}painter.rotate(rotate);QPixmap pix(\":wait\");painter.drawPixmap(-pix.width()/2,-pix.height()/2,pix);}
【领 QT开发教程 学习资料, 点击下方链接莬费领取↓↓ ,先码住不迷路~】
点击这里:
标签: