支持左右渐变
public class EdgeGradientLayout extends FrameLayout {
private Paint mPaint;
//左侧渐变
private boolean leftGradient;
//右侧渐变
private boolean rightGradient;
private int mWidth;
private int mHeight;
private int mDrawSize = 100;
//渐变颜色
private int[] mGradientColors = { 0xffffffff, 0x00000000 };
//渐变位置
private float[] mGradientPosition = new float[] { 0, 1 };
public EdgeGradientLayout (Context context) {
this(context, null);
}
public EdgeGradientLayout (Context context, AttributeSet attrs) {
super(context, attrs);
}
private void initShader() {
if (mPaint == null) {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
mPaint.setShader(new LinearGradient(0, 0, 0, mDrawSize, mGradientColors, mGradientPosition,
Shader.TileMode.CLAMP));
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
initShader();
mWidth = getWidth();
mHeight = getHeight();
}
@Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
int layerSave = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
boolean drawChild = super.drawChild(canvas, child, drawingTime);
float offset = (mHeight - mWidth) / 2f;
if (leftGradient) {
int saveCount = canvas.save();
canvas.rotate(270, mWidth / 2f, mHeight / 2f);
canvas.translate(0, offset);
canvas.drawRect(0 - offset, 0, mWidth + offset, mDrawSize, mPaint);
canvas.restoreToCount(saveCount);
}
if (rightGradient) {
int saveCount = canvas.save();
canvas.rotate(90, mWidth / 2f, mHeight / 2f);
canvas.translate(0, offset);
canvas.drawRect(0 - offset, 0, mWidth + offset, mDrawSize, mPaint);
canvas.restoreToCount(saveCount);
}
canvas.restoreToCount(layerSave);
return drawChild;
}
public void setLeftGradient(boolean leftGradient) {
this.leftGradient = leftGradient;
}
public void setRightGradient(boolean rightGradient) {
this.rightGradient = rightGradient;
}
public void setDrawSize(int mDrawSize) {
this.mDrawSize = mDrawSize;
}
}