Creating a gradient tool

Simple algebra to create effects along a gradient. I thought of a nice new feature for the Delaunay Android app, the app ‘polygonises’ pictures by overlaying triangles onto a photo, I guessed it’d look good if the opacity could be controlled in a similar way to a gradient tool in a drawing application. Having the user tap once to mark the start of the gradient and again to mark the end is easy, but the gradient could be at any angle across the screen, to calculate the opacity for a triangle/point we need to use some basic algebra – I say basic; I did struggle a little with this, and there may be better ways of doing it.

In the processing code below there are 5 points, and a line representing a linear gradient tool created by the user. The code calculates the opacity for each point based on its relation to the gradient vector.

Here’s an example of the code running in a prototype Delaunay triangulation app, two gradient controls – controlling the fill and wireframe opacity: