Pixel drawing app


(Pharap) #41

The Arduino version of what most people would call a clamp function.
(Wikipedia classes it as being part of ‘computer graphics’,
but it’s useful for things other than graphics.)

Sadly Arduino’s constrain is actually a macro rather than a function.

It’s implemented as:

#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))

As a function that would look something like:

template<typename T>
constexpr T constrain(T value, T low, T high)
{
	return ((value < low) ? low : ((value > high) ? high : value));
}

(Don’t worry if you don’t understand the template or constexpr parts.)


(As of C++17 the C++ standard library has a std::clamp function.)


For the record, one reason to prefer preempting the cursor movement instead of moving and then ‘constraining’ is because preempting tends to use less progmem, even if it looks like it uses more code.
It also avoids the need to worry about overflow.
(Sometimes less is more and more is less.)

The approach of using INVERT is certainly better. (I’d forgotten that was even an option.)
And the pencil icon does look better.

(Though I’d suggest using some constexpr variables instead of magic numbers like 7, -7 and + 7.)