方法:
如下图,一个三角形 ABC ,延长任意两条边做一个平行四边形。
我们知道,向量 AB + 向量 BC 是 向量 AD 。AB 与 AC 不平行,可做为平面内一组基底。这样,平面内所有点都可以根据 AB 和 AC 以及点 A 得到。我们只需要得到平行四边形 ABDC 中的点,然后把三角形 BCD 中的点对称到 ABC 中就可以了。
代码实现(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;
}
运行结果如图:
取了 10000 个点,看起来分布还算均匀,对于要求不太高的场景应该够用了~