Update picker preview upon drag

This commit is contained in:
Moez Bhatti
2018-03-24 03:43:32 -04:00
parent e9232c639c
commit d7df80cc81
@@ -34,6 +34,12 @@ class HSVPickerView @JvmOverloads constructor(context: Context, attrs: Attribute
private var min: Float = 0f
private var max = 0f
private var hue = 0f
set(value) {
field = value
updateHue()
}
init {
View.inflate(context, R.layout.hsv_picker_view, this)
@@ -49,8 +55,16 @@ class HSVPickerView @JvmOverloads constructor(context: Context, attrs: Attribute
}
MotionEvent.ACTION_MOVE -> {
swatch.x = (event.rawX + swatchX + min).within(min, max)
swatch.y = (event.rawY + swatchY + min).within(min, max)
// Calculate the new x/y position
val x = (event.rawX + swatchX + min).within(min, max)
val y = (event.rawY + swatchY + min).within(min, max)
swatch.x = x
swatch.y = y
val range = max - min
val hsv = floatArrayOf(hue, (x - min) / range, 1 - (y - min) / range)
swatchPreview.setBackgroundTint(Color.HSVToColor(hsv))
}
else -> return@setOnTouchListener false
@@ -67,22 +81,25 @@ class HSVPickerView @JvmOverloads constructor(context: Context, attrs: Attribute
}
fun setColor(color: Int) {
swatchPreview.setBackgroundTint(color)
// Convert the rgb color to HSV
val hsv = FloatArray(3).apply { Color.colorToHSV(color, this) }
val hsv = FloatArray(3).apply {
Color.colorToHSV(color, this)
hue = this[0]
}
// Set the position of the swatch
setupBounds()
val range = max - min
swatch.x = range * hsv[1] + min
swatch.y = range * (1 - hsv[2]) + min
}
// Change the HSV saturation and lightness, for tinting the gradient
hsv[1] = 1f
hsv[2] = 1f
swatchPreview.setBackgroundTint(color)
saturation.setBackgroundTint(Color.HSVToColor(hsv))
private fun updateHue() {
val hsv = floatArrayOf(hue, 1f, 1f)
val tint = Color.HSVToColor(hsv)
saturation.setBackgroundTint(tint)
}
}