Please forgive the poor English in advance.
hello! I am currently implementing view widget using QGraphicsView & QGraphicsItem.
Is there any way to draw gridlines only inside a circle?
Rectangles are fine, but trying to draw them inside a circle is a pain.
Below is sample code.
for(int x = rect.left(); x <= rect.right(); x) {
painter->drawLine(QPointF(x, rect.top()), QPointF(x, rect.bottom()));
}
for(int y = rect.top(); y <= rect.bottom(); y) {
painter->drawLine(QPointF(rect.left(), y), QPointF(rect.right(), y));
}
here is my current state --> Current grid line result
result what i want is looks like --> Reuslt example what I want
I don't want to show grid line out of circle bound.
If you have any good ideas, please reply.
thank you!
CodePudding user response:
It's just a matter of tigronometry calculation. From the position on the X or Y axis you can calculate the angle to go to the point on the circle using arc sin and arc cosine. The code below should work
#include <math.h>
class Point
{
public:
double X = 0.0;
double Y = 0.0;
};
int main()
{
double radius = 10.0;
double stepx = 2.0;
double stepy = 2.0;
int stepsInX = radius / stepx;
int stepsInY = radius / stepy;
// this is just for positive X (need another loop for negative X)
for (int i = 0; i <= stepsInX; i )
{
double angle = acos(i*stepx / radius);
double y = radius * sin(angle);
Point p1;
p1.X = i * stepx;
p1.Y = y;
Point p2;
p2.X = i * stepx;
p2.Y = -y;
drawLine(p1, p2);
}
// this is just for positive Y (need another loop for negative Y)
for (int i = 0; i <= stepsInY; i )
{
double angle = asin(i * stepy / radius);
double x = radius * cos(angle);
Point p1;
p1.X = x;
p1.Y = i * stepy;
Point p2;
p2.X = -x;
p2.Y = i * stepy;
drawLine(p1, p2);
}
}
void drawLine(Point const& p1, Point const& p2)
{
// your code to draw line here
}