optimize render performance for rounded corners on Android
This commit is contained in:
parent
8bc029dc14
commit
48728d6d19
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue