[android] accept floating numbers during core->platform color conversion

This commit is contained in:
Łukasz Paczos
2019-06-18 12:58:23 +02:00
committed by Łukasz Paczos
parent c3e94a0648
commit 55527d0412
2 changed files with 29 additions and 5 deletions

View File

@@ -124,14 +124,16 @@ public class ColorUtils {
*/
@ColorInt
public static int rgbaToColor(@NonNull String value) {
Pattern c = Pattern.compile("rgba?\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,?\\s*(\\d+\\.?\\d*)?\\s*\\)");
// we need to accept and floor float values as well, as those can come from core
Pattern c = Pattern.compile("rgba?\\s*\\(\\s*(\\d+\\.?\\d*)\\s*,\\s*(\\d+\\.?\\d*)\\s*,\\s*(\\d+\\.?\\d*)\\s*,"
+ "?\\s*(\\d+\\.?\\d*)?\\s*\\)");
Matcher m = c.matcher(value);
if (m.matches() && m.groupCount() == 3) {
return Color.rgb(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)),
Integer.parseInt(m.group(3)));
return Color.rgb((int) Float.parseFloat(m.group(1)), (int) Float.parseFloat(m.group(2)),
(int) Float.parseFloat(m.group(3)));
} else if (m.matches() && m.groupCount() == 4) {
return Color.argb((int) (Float.parseFloat(m.group(4)) * 255), Integer.parseInt(m.group(1)),
Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)));
return Color.argb((int) (Float.parseFloat(m.group(4)) * 255), (int) Float.parseFloat(m.group(1)),
(int) Float.parseFloat(m.group(2)), (int) Float.parseFloat(m.group(3)));
} else {
throw new ConversionException("Not a valid rgb/rgba value");
}

View File

@@ -0,0 +1,22 @@
package com.mapbox.mapboxsdk.utils
import android.graphics.Color
import junit.framework.Assert
import org.junit.Test
class ColorUtilsTest {
@Test
fun rgbaToColor_decimalComponent() {
val input = "rgba(255,128.0000952303,0,0.7)"
val result = ColorUtils.rgbaToColor(input)
Assert.assertEquals(Color.argb(255, 128, 0, (0.7 * 255).toInt()), result)
}
@Test
fun rgbaToColor_decimalComponent_floor() {
val input = "rgba(255,128.70123,0,0.7)"
val result = ColorUtils.rgbaToColor(input)
Assert.assertEquals(Color.argb(255, 128, 0, (0.7 * 255).toInt()), result)
}
}