From 48728d6d192d0d0a694af04cec1b2a0862a56eb6 Mon Sep 17 00:00:00 2001 From: Dmitry Gladkov Date: Wed, 20 Jan 2016 14:11:24 +0200 Subject: [PATCH] optimize render performance for rounded corners on Android --- .../BV/LinearGradient/LinearGradientView.java | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/android/src/main/java/com/BV/LinearGradient/LinearGradientView.java b/android/src/main/java/com/BV/LinearGradient/LinearGradientView.java index 9fd4350..45b7d58 100644 --- a/android/src/main/java/com/BV/LinearGradient/LinearGradientView.java +++ b/android/src/main/java/com/BV/LinearGradient/LinearGradientView.java @@ -6,7 +6,7 @@ import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; -import android.graphics.Rect; +import android.graphics.Path; import android.graphics.RectF; import android.graphics.Shader; import android.view.View; @@ -14,6 +14,8 @@ import android.view.View; public class LinearGradientView extends View { private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private Path mPathForBorderRadius; + private RectF mTempRectForBorderRadius; private LinearGradient mShader; private float[] mLocations; @@ -60,12 +62,14 @@ public class LinearGradientView extends View { public void setBorderRadius(float borderRadius) { mBorderRadius = borderRadius; + updatePath(); drawGradient(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mSize = new int[]{w, h}; + updatePath(); drawGradient(); } @@ -82,18 +86,27 @@ public class LinearGradientView extends View { invalidate(); } + private void updatePath() { + if (mPathForBorderRadius == null) { + mPathForBorderRadius = new Path(); + mTempRectForBorderRadius = new RectF(); + } + mPathForBorderRadius.reset(); + mTempRectForBorderRadius.set(0f, 0f, (float) mSize[0], (float) mSize[1]); + mPathForBorderRadius.addRoundRect( + mTempRectForBorderRadius, + mBorderRadius, + mBorderRadius, + Path.Direction.CW); + } + @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); - if (mBorderRadius != 0f) { - RectF clipBounds = new RectF(canvas.getClipBounds()); - canvas.drawRoundRect( - clipBounds, - mBorderRadius, - mBorderRadius, - mPaint); - } else { + if (mPathForBorderRadius == null) { canvas.drawPaint(mPaint); + } else { + canvas.drawPath(mPathForBorderRadius, mPaint); } } }