如今智能手机的普及,为了使自己的app在大众面前用的更舒心,首先好的效果是必须的,下面我首先贴上一张效果图,大家看看这个该如何实现呢?
对于大多数人来看,这还不简单,直接在帧布局里面套一个线性布局,其中线性布局里面放内容,其次再在帧布局的顶部和底部分别放两张渐变图片不就好了。我想说的是,这么做虽然也可以,但是却为了实现效果而加入页面嵌套,导致页面多重绘制,简单页面还好,对于复杂点的页面,可能会影响页面性能甚至卡顿。
所以,我的实现思路就是,直接重写线性布局,在该布局绘制的时候,分别在顶部和底部画上渐变图片,而且为了实现渐变线的可定制性,图片部分也是使用GradientDrawable来控制的。
具体实现逻辑如下:
public class GradientLayout extends LinearLayout {
private int startColor;
private int endColor;
private int gradientHeight;
private Bitmap topBmp;
private Bitmap bottomBmp;
private boolean gradientTop;
private boolean gradientBottom;
public GradientLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.GradientLayout);
startColor = ta.getColor(R.styleable.GradientLayout_gradientStartColor, 0);
endColor = ta.getColor(R.styleable.GradientLayout_gradientEndColor, 0);
gradientHeight = ta.getDimensionPixelOffset(R.styleable.GradientLayout_gradientHeight, 0);
gradientTop = ta.getBoolean(R.styleable.GradientLayout_gradientTop, true);
gradientBottom = ta.getBoolean(R.styleable.GradientLayout_gradientBottom, true);
ta.recycle();
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (startColor == 0 && endColor == 0) return;
if (gradientHeight == 0) return;
if (!gradientTop && !gradientBottom) return;
if (null == topBmp) {
topBmp = getBitmap(true);
}
if (null == bottomBmp) {
bottomBmp = getBitmap(false);
}
if (gradientTop) {
canvas.drawBitmap(topBmp, 0, 0, null);
}
if (gradientBottom) {
canvas.drawBitmap(bottomBmp, 0, getHeight() - gradientHeight, null);
}
}
private Bitmap getBitmap(boolean isTop) {
int firstColor = isTop ? startColor : endColor;
int secondColor = isTop ? endColor : startColor;
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{firstColor, secondColor});
Bitmap bmp = Bitmap.createBitmap(getWidth(), gradientHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
gd.setBounds(0, 0, getWidth(), gradientHeight);
gd.draw(canvas);
return bmp;
}
}