我在矩形内画了四分之一的圆。
矩形:
UIView *Rectangle = [[UIView alloc] initWithFrame:CGRectMake(0,0,[[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height-292)];
Rectangle.backgroundColor = [UIColor lightGrayColor];
Rectangle.layer.zPosition = -5;
四分之一圈:
CGPoint center;
center.x = 0;
center.y = 0;
float radius = [[UIScreen mainScreen] bounds].size.width;
UIBezierPath *circle = [UIBezierPath bezierPathWithArcCenter:center
radius:radius
startAngle:0
endAngle:M_PI
clockwise:YES];
CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[circle CGPath]];
然后我在 View 中添加了矩形,并在矩形内添加了圆:
[self.view addSubview:Rectangle];
[Rectangle.layer addSublayer:circleLayer];
然后我开始绘制我认为是点的宽度为 1 和高度为 1 的小矩形,并使用 for 循环将它们随机添加到 View 中,用绿色为圆圈内的点着色,用红色为圆圈外的点着色
int compteurPointsinCercle = 0 ;
int compteurPointsOutCercle = 0 ;
float XcenterCircle = center.x;
float YcenterCircle = center.y;
for (int i = 0 ; i < 50000 ; i++ )
{
float xvalue = arc4random_uniform([[UIScreen mainScreen] bounds].size.width);
float yvalue = arc4random_uniform([[UIScreen mainScreen] bounds].size.height-292);
// (x - center_x)^2 + (y - center_y)^2 < radius^2
float valeurPoint = (xvalue - XcenterCircle)*2 + (yvalue -YcenterCircle)*2;
NSLog(@"(Inside for), valeurPoint is : %f",valeurPoint);
if ( valeurPoint < (radius*2) )
{
// Point is inside of circle (green color)
compteurPointsinCercle++;
UIView *Rectangle2 = [[UIView alloc] initWithFrame:CGRectMake(xvalue,yvalue,1,1)];
Rectangle2.backgroundColor = [UIColor greenColor];
[self.view addSubview:Rectangle2];
}
else if ( valeurPoint > (radius*2) )
{
// Point is outside of circle (red color)
compteurPointsOutCercle++;
UIView *Rectangle2 = [[UIView alloc] initWithFrame:CGRectMake(xvalue,yvalue,1,1)];
Rectangle2.backgroundColor = [UIColor redColor];
[self.view addSubview:Rectangle2];
}
}
我使用这个测试点是否在圆内:
float valeurPoint = (xvalue - XcenterCircle)*2 + (yvalue -YcenterCircle)*2;
其中 xvalue
和 yvalue
是将要创建的点的坐标,XcenterCircle
和 YcenterCircle
是圆心的坐标。
我有问题,因为它给了我这个结果(如果点在圆内或不在圆内,它会正确测试:圆内的一部分点被认为在圆外):
你能告诉我我做错了什么吗?我怎样才能准确地找到圆圈内的点?
最佳答案
*
不是幂运算,是乘法。
float valeurPoint = (xvalue - XcenterCircle) * (xvalue - XcenterCircle) + (yvalue -YcenterCircle)*(yvalue -YcenterCircle);
if ( valeurPoint < (radius * radius) )
应该可以解决你的问题
或者使用pow
函数:
float valeurPoint = pow((xvalue - XcenterCircle), 2) + pow((yvalue -YcenterCircle), 2);
也可以直接使用hypot
函数(虽然由于sqrt
计算性能会稍微差一些)
float distance = hypotf((xvalue - XcenterCircle), (yvalue -YcenterCircle));
if (distance < radius)
编辑:
感谢@Alex 的建议。最好的解决方案是使用 native 方法 -[UIBerierPath containsPoint:]
。那么您根本不需要计算距离。
关于ios - Objective-C - 如何知道点是否在四分之一圆内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33568636/