Line data Source code
1 : import 'dart:math' show min, max; 2 : import 'dart:math' as math; 3 : import 'dart:ui'; 4 : 5 : import '../../geometry.dart'; 6 : import 'offset.dart'; 7 : import 'size.dart'; 8 : import 'vector2.dart'; 9 : 10 : export 'dart:ui' show Rect; 11 : 12 : extension RectExtension on Rect { 13 : /// Creates an [Offset] from this [Rect] 14 0 : Offset toOffset() => Offset(width, height); 15 : 16 : /// Creates a [Vector2] starting in top left and going to [width, height]. 17 4 : Vector2 toVector2() => Vector2(width, height); 18 : 19 : /// Converts this [Rect] into a [math.Rectangle]. 20 6 : math.Rectangle toMathRectangle() => math.Rectangle(left, top, width, height); 21 : 22 : /// Converts this [Rect] into a Rectangle from flame-geom. 23 1 : Rectangle toGeometryRectangle() { 24 1 : return Rectangle( 25 2 : position: topLeft.toVector2(), 26 2 : size: size.toVector2(), 27 : ); 28 : } 29 : 30 : /// Whether this [Rect] contains a [Vector2] point or not 31 0 : bool containsPoint(Vector2 point) => contains(point.toOffset()); 32 : 33 : /// Whether the segment formed by [pointA] and [pointB] intersects this [Rect] 34 0 : bool intersectsSegment(Vector2 pointA, Vector2 pointB) { 35 0 : return min(pointA.x, pointB.x) <= right && 36 0 : min(pointA.y, pointB.y) <= bottom && 37 0 : max(pointA.x, pointB.x) >= left && 38 0 : max(pointA.y, pointB.y) >= top; 39 : } 40 : 41 : /// Whether the [LineSegment] intersects the [Rect] 42 0 : bool intersectsLineSegment(LineSegment segment) { 43 0 : return intersectsSegment(segment.from, segment.to); 44 : } 45 : 46 0 : List<Vector2> toVertices() { 47 0 : return [ 48 0 : topLeft.toVector2(), 49 0 : topRight.toVector2(), 50 0 : bottomRight.toVector2(), 51 0 : bottomLeft.toVector2(), 52 : ]; 53 : } 54 : 55 : /// Creates bounds in from of a [Rect] from a list of [Vector2] 56 0 : static Rect fromBounds(List<Vector2> pts) { 57 0 : final minX = pts.map((e) => e.x).reduce(min); 58 0 : final maxX = pts.map((e) => e.x).reduce(max); 59 0 : final minY = pts.map((e) => e.y).reduce(min); 60 0 : final maxY = pts.map((e) => e.y).reduce(max); 61 0 : return Rect.fromPoints(Offset(minX, minY), Offset(maxX, maxY)); 62 : } 63 : 64 : /// Constructs a rectangle from its center point (specified as a Vector2), 65 : /// width and height. 66 0 : static Rect fromVector2Center({ 67 : required Vector2 center, 68 : required double width, 69 : required double height, 70 : }) { 71 0 : return Rect.fromLTRB( 72 0 : center.x - width / 2, 73 0 : center.y - height / 2, 74 0 : center.x + width / 2, 75 0 : center.y + height / 2, 76 : ); 77 : } 78 : }