Feature Request: setColor(color: Int)
dgadelha opened this issue · comments
Hello,
First of all I'd like to thank for this library, it's great: simple and beautiful.
The main thing it misses right now is the following method: setColor(color: Int)
, allowing us to change the selected color.
Thanks!
Also me I would like to have this method.
After much look around in code I found a solution for setColor but this method has to be called after the seekBar is rendered.
Added the below method in ColorSeekBar.kt
fun setColor(color: Int) {
val barLeft: Int = paddingStart.toInt()
val barRight: Int = (measuredWidth.toFloat() - paddingEnd).toInt()
var newColor = barLeft
var xvalue = barLeft
for (i in barLeft..barRight) {
if (color == pickColor(i.toFloat(), measuredWidth)) {
newColor = pickColor(i.toFloat(), measuredWidth)
xvalue = i
break
}
}
thumbX = xvalue.toFloat()
thumbPaint.color = newColor
invalidate()
}
And if you want the onColorChangeListener then add the below line of Code after thumbPaint.color = newColor
:
colorChangeListener?.onColorChangeListener(newColor)
Small addition to the post above: it searches to the nearest color, because in most cases it will not find exact same color.
fun setColor(color: Int) {
val barLeft: Int = paddingStart.toInt()
val barRight: Int = (measuredWidth.toFloat() - paddingEnd).toInt()
var minDistance = Int.MAX_VALUE
var distance : Int
var resultIndex = 0
for (i in barLeft..barRight) {
val pickedColor = pickColor(i.toFloat(), measuredWidth)
distance = colorDistance(pickedColor, color)
if (minDistance > distance) {
minDistance = distance
resultIndex = i
}
}
thumbX = resultIndex.toFloat()
thumbPaint.color = pickColor(resultIndex.toFloat(), measuredWidth)
invalidate()
}
fun colorDistance(c1 : Int, c2 : Int) : Int {
return Math.abs(Color.red(c1) - Color.red(c2)) + Math.abs(Color.green(c1) - Color.green(c2)) + Math.abs(Color.blue(c1) - Color.blue(c2))
}