PerspectiveTransform.fromTransformedSquare constructor

PerspectiveTransform.fromTransformedSquare(
  1. List<Position<num>> vertices
)

Creates a PerspectiveTransform that transforms a 1x1 square into the given quadrilateral, expressed as a list of its vertices.

Implementation

factory PerspectiveTransform.fromTransformedSquare(
  List<Position> vertices,
) {
  assert(vertices.length == 4);
  final p1 = vertices[0].toDouble(),
      p2 = vertices[1].toDouble(),
      p3 = vertices[2].toDouble(),
      p4 = vertices[3].toDouble();

  final dx3 = p1.x - p2.x + p3.x - p4.x;
  final dy3 = p1.y - p2.y + p3.y - p4.y;
  if (dx3 == 0 && dy3 == 0) {
    // Affine
    return PerspectiveTransform([
      p2.x - p1.x, p2.y - p1.y, 0, //
      p3.x - p2.x, p3.y - p2.y, 0, //
      p1.x, p1.y, 1, //
    ]);
  } else {
    final dx1 = p2.x - p3.x;
    final dx2 = p4.x - p3.x;
    final dy1 = p2.y - p3.y;
    final dy2 = p4.y - p3.y;
    final denominator = dx1 * dy2 - dx2 * dy1;
    final a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
    final a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
    return PerspectiveTransform([
      p2.x - p1.x + a13 * p2.x, p2.y - p1.y + a13 * p2.y, a13, //
      p4.x - p1.x + a23 * p4.x, p4.y - p1.y + a23 * p4.y, a23, //
      p1.x, p1.y, 1 //
    ]);
  }
}