Finding an Affine Transform the Traditional Way with three 2D point correspondences in Swift

My previous post provided links and Swift sample code to introduce Simplex Affine Mapping (SAM), a technique that can be used to find an affine transform from one triangle to another triangle in 2D space.

Today I saw the StackOverflow post “Transfer coordinates from one triangle to another triangle.” It struck me as a good idea to offer code for the more traditional way of finding the affine transform.

To find the affine transform from one triangle to another triangle, and using StackOverflow user MBo’s naming conventions, we’ll do the following in Swift:

  1. Populate two 3x3 matrices with the three 2D point pairs.
  2. M * A = B, where M = affine matrix, A = “from” points, B = “to” points, all expressed as 3x3 matrices
  3. M = B * Inv(A)
  4. Find Inv(A), the inverse of matrix A (the “from” points)
  5. Create a CGAffineTransform from the 3x3 matrix M

Here’s a handy guide explaining how to find the inverse of a matrix:

We’ll import CoreGraphics and create our own Triangle and Matrix3x3 types. We import Foundation framework just so that we can extend NumberFormatter to add a few string( ) function overloads used to print statements to the console as we test the transform(from:to:) function.

Paste the following sample code into an XCode12 playground and run it.

Happy New Year!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store