|
这是我之前做过的项目,源码贴上。- /**
- * @brief 定义圆的结构体
- * 因为画布大小为1440 * 900,
- * 所以2个字节的short类型就足够
- */
- struct Circle
- {
- short x;
- short y;
- short r;
- };
- /**
- * @author yuliuchuan
- * @date 2015-04-10
- * 因为绘图的零度是三点钟方向,
- * 所以用余弦定理计算圆弧上某点的角度,
- * acos()返回值为[0,PI]。
- * 如果点在圆心的上方,则用360减去返回值。
- * 由于物理坐标是以左上角为原点,
- * 逻辑坐标要以左下角为原点,
- * 所以需要进行变换。
- * 即 x1 = x0,y1 = height - y0。
- */
- double PainterArea::getAngle(CirclePoint *cl, Point *p1)
- {
- int centerX = cl->x;
- int centerY = rect.height() - cl->y;
- int radius = cl->r;
- double px = p1->x;
- double py = rect.height() - p1->y;
- //3点钟方向
- double p3x = centerX + radius;
- double p3y = centerY;
- double a2 = (px - p3x) * (px - p3x) + (py - p3y) * (py - p3y);
- double b2 = radius * radius;
- //double c2 = b2;
- double cosa = (b2 * 2 - a2) / (2 * b2);
- //任意角度的余弦值为[-1.0,1.0];
- //上式可简化为1 - a2 / (2 * b2),
- //所以如果值小于-1.0,则应取-1.0。
- if(cosa < - 1.0){
- cosa = -1.0;
- }
- //换算成角度
- double angle = acos(cosa) / 3.1415926 * 180;
- #ifdef QT_DEBUG
- qDebug()<<"angle:"<<angle;
- #endif
- if(py < centerY){
- return (360 - angle);
- }
- return angle;
- }
- /**
- * @author yuliuchuan
- * @date 2015-04-10
- * 计算变换后的圆的外接矩形
- */
- QRectF PainterArea::getCircleRect(Circle *cl)
- {
- return QRectF(cl->x - cl->r,rect.height() - cl->y - cl->r,2 * cl->r,2 * cl->r);
- }
- /**
- * @author yuliuchuan
- * @date 2015-04-10
- * 计算变换后的圆的外接矩形
- */
- QRectF PainterArea::getCircleRect(int x, int y, int r)
- {
- return QRectF(x - r,rect.height() - y - r,2 * r,2 *r);
- }
- /**
- * @author yuliuchuan
- * @date 2015-04-10
- * 计算绘制圆弧时的起始角度和跨越角度。
- */
- int *PainterArea::get2Angles(CirclePoint *cl, Point *p1, Point *p2)
- {
- int *angles = new int[2];
- angles[0] = 0;
- angles[1] = 0;
- angles[0] = int(getAngle(cl,p1));
- angles[1] = int(getAngle(cl,p2));
- #ifdef QT_DEBUG
- qDebug()<<"angle1:"<<p1->x<<p1->y<<angles[0];
- qDebug()<<"angle2:"<<p2->x<<p2->y<<angles[1];
- #endif
- angles[0] = angles[0];
- //如果末点角度小于起点角度,则加上360度后与起点角度求差,得到跨越角度
- angles[1] = angles[1] < angles[0] ? (angles[1] + 360 - angles[0]) : (angles[1] - angles[0]);
- //在QT中,一度用16表示,
- //正数代表逆时针,负数代表逆时针。
- angles[0] *= (-16);
- angles[1] *= (-16);
- return angles;
- }
复制代码 使用方法:- painter.drawEllipse(getCircleRect(cl));
复制代码 还有一个,半径这个参数,这个你会算吧?
|
|