在三角形中隨機(jī)取點(diǎn)

方法:

如下圖,一個三角形 ABC ,延長任意兩條邊做一個平行四邊形。

三角形 - 平行四邊形.png

我們知道,向量 AB + 向量 BC 是 向量 AD 。AB 與 AC 不平行,可做為平面內(nèi)一組基底。這樣,平面內(nèi)所有點(diǎn)都可以根據(jù) AB 和 AC 以及點(diǎn) A 得到。我們只需要得到平行四邊形 ABDC 中的點(diǎn),然后把三角形 BCD 中的點(diǎn)對稱到 ABC 中就可以了。

代碼實現(xiàn)(iOS_Objective-C):

為了簡單,選用了 UIBezier 方式在 UIView 中繪制。

- (void)drawRect:(CGRect)rect {
CGFloat viewWidth = self.frame.size.width;
CGFloat viewHeight = self.frame.size.height;

CGFloat x0 = arc4random() % (int)viewWidth;
CGFloat y0 = arc4random() % 50;

CGFloat x1 = arc4random() % 100;
CGFloat y1 = arc4random() % 100 + viewHeight - 100;

CGFloat x2 = arc4random() % 80 + viewWidth - 80;
CGFloat y2 = arc4random() % 80 + viewHeight - 80;

CGPoint point0 = CGPointMake(x0, y0);
CGPoint point1 = CGPointMake(x1, y1);
CGPoint point2 = CGPointMake(x2, y2);

UIBezierPath *bezierPath = [[UIBezierPath alloc] init];

[bezierPath moveToPoint:point0];
[bezierPath addLineToPoint:point1];
[bezierPath addLineToPoint:point2];
[bezierPath addLineToPoint:point0];

[[UIColor blackColor] set];
[bezierPath stroke];

for (int index = 0; index < 10000; index++){
    UIBezierPath *pointBezierPath = [[UIBezierPath alloc] init];
    CGPoint point = [self getPointWithPoint0:point0 Point1:point1 Point2:point2];
    [pointBezierPath addArcWithCenter:point radius:1 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    [[UIColor redColor] set];
    [pointBezierPath stroke];
    [pointBezierPath fill];
}
}

- (CGPoint)getPointWithPoint0:(CGPoint)point0 Point1:(CGPoint)point1 Point2:(CGPoint) point2{

CGPoint vector0 = CGPointMake(point1.x - point0.x, point1.y - point0.y);
CGPoint vector1 = CGPointMake(point2.x - point0.x, point2.y - point0.y);

CGFloat t1 = 0;
CGFloat t2 = 0;

do {
    
    t1 = (CGFloat)(1 + arc4random() % 99) / 100;
    t2 = (CGFloat)(1 + arc4random() % 99) / 100;
    
}while( t1 + t2 ==1 );

if (t1 + t2 >= 1){
    t1 = 1 - t1;
    t2 = 1 - t2;
}

CGPoint point = CGPointMake(t1 * vector0.x + t2 * vector1.x + point0.x, t1 * vector0.y + t2 * vector1.y + point0.y);
return point;
}

運(yùn)行結(jié)果如圖:

三角形隨機(jī)取點(diǎn).png

取了 10000 個點(diǎn),看起來分布還算均勻,對于要求不太高的場景應(yīng)該夠用了~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容