我在矩形內畫了四分之一圓。客觀C - 如何知道點是否在四分之一圓內?
矩形:
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;
Cirlce季:
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]];
然後,我添加矩形視圖中,並加入在矩形內圓:
[self.view addSubview:Rectangle];
[Rectangle.layer addSublayer:circleLayer];
然後我的tarted繪圖1米的寬度和1米高度的小矩形,我認爲爲點,並隨機加入它們與一個for循環的視圖,着色點的綠色和點的圓的外側圓內與紅色
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
是圓心的coordiantes。
我有什麼錯的,因爲它給了我這樣的結果(它正確dosent測試,如果該點位於圓圈內或不:圓圈內的點的一部分,被認爲是外):
你能告訴我我在做什麼錯嗎?以及我如何才能確切地說明圈內的點?
也許是這樣的:http://stackoverflow.com/questions/10831370/how-to-check-if-touch-point-is-on-uibezierpath-ios – Alex
@Alex這是一個很好的解決方案。 – Sulthan