Replaced Paint.setAlpha() with Paint.setColor() to reduce unnecessary allocations (#1929)
Resolves #1928
This pull request attempts to remove ColorSpace.Named[] allocations when calling Paint.setAlpha(). These changes will fix the issue only when using RGB colors.
diff --git a/lottie/src/main/java/com/airbnb/lottie/animation/LPaint.java b/lottie/src/main/java/com/airbnb/lottie/animation/LPaint.java
index ea8f1e8..ab82411 100644
--- a/lottie/src/main/java/com/airbnb/lottie/animation/LPaint.java
+++ b/lottie/src/main/java/com/airbnb/lottie/animation/LPaint.java
@@ -1,8 +1,11 @@
package com.airbnb.lottie.animation;
+import static com.airbnb.lottie.utils.MiscUtils.clamp;
+
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
+import android.os.Build;
import android.os.LocaleList;
import androidx.annotation.NonNull;
@@ -35,4 +38,21 @@
public void setTextLocales(@NonNull LocaleList locales) {
// Do nothing.
}
+
+ /**
+ * Overrides {@link android.graphics.Paint#setAlpha(int)} to avoid
+ * unnecessary {@link android.graphics.ColorSpace.Named ColorSpace$Named[] }
+ * allocations when calling this method in Android 29 or lower.
+ *
+ * @param alpha set the alpha component [0..255] of the paint's color.
+ */
+ @Override
+ public void setAlpha(int alpha) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ int color = getColor();
+ setColor((clamp(alpha, 0, 255) << 24) | (color & 0xFFFFFF));
+ } else {
+ super.setAlpha(clamp(alpha, 0, 255));
+ }
+ }
}
diff --git a/lottie/src/main/java/com/airbnb/lottie/animation/content/FillContent.java b/lottie/src/main/java/com/airbnb/lottie/animation/content/FillContent.java
index 35f472f..46732a8 100644
--- a/lottie/src/main/java/com/airbnb/lottie/animation/content/FillContent.java
+++ b/lottie/src/main/java/com/airbnb/lottie/animation/content/FillContent.java
@@ -98,9 +98,9 @@
return;
}
L.beginSection("FillContent#draw");
- paint.setColor(((ColorKeyframeAnimation) colorAnimation).getIntValue());
+ int color = ((ColorKeyframeAnimation) this.colorAnimation).getIntValue();
int alpha = (int) ((parentAlpha / 255f * opacityAnimation.getValue() / 100f) * 255);
- paint.setAlpha(clamp(alpha, 0, 255));
+ paint.setColor((clamp(alpha, 0, 255) << 24) | (color & 0xFFFFFF));
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());