Kotlin color picker. Part 1.
Hi, everyone. I have few ideas to share, hope it will help someone to write better Android apps. This time, I’ll share with you how to create color picker by using just Kotlin, Android SDK and your imagination.
I’ll start with a simple implementation, later we’ll find the way to improve it and embed in a simple project. You could find a source code right here. Download it and have fun!
Looks great! And it’s time to share with you how this thing works. But before we start, make sure you know what is Kotlin, git, why we need canvas here and how to build Android project using Gradle. Let’s go!
How it works?
The first thing you need to know about this example — no Java here. All source code are pure Kotlin. And if you have some questions about it —feel free to let me know.
Second thing — we are using canvas here. Most views in Android are just some Bitmaps or shapes that are drawn on the canvas. In our case, we just use a line, LinearGradient shader and a little trick with round StrokeCup for Paint that makes our line rounded.
Paint is the king here — an instance of this class will draw anything we want. You could see handy apply function here, that makes any bad API a little bit better.
Since we have no bitmaps, it allows us to use any colors for gradient and even do it dynamically if needed.
The biggest problem in this example — picking of the right color. The gradient is good but how we’ll know exact color we chose? Check out util methods we have below:
Since our picker is one-dimensional, we get a pretty simple function that will allow us to interpolate color between those we used in the colors array.
The important thing here — we interpolate each color channel separately to get accurate color. Want to know what would happen if we’ll pass raw colors to avg function? Download source code and check this out!
What I like most about this part — we don’t need to create a util class anymore(thanks, Kotlin). Also @FloatRange will check for us if we use our functions with right values at compile time .
Now let’s have a look at picker itself. It’s pretty straightforward, and size of all elements depends only on the size of view itself.
And this is not a production-ready approach yet. Sure you know why we have @SuppressWarnings(“MagicNumber”) here😏
In next part, we’ll prepare this picker for production. Stay tuned!
P.S. Questions, ideas and pull-requests highly appreciated.