如今智能手機的普及,為了使自己的app在大眾面前用的更舒心,首先好的效果是必須的,下面我首先貼上一張效果圖,大家看看這個該如何實現呢?
帶漸變特效的布局.png
對于大多數人來看,這還不簡單,直接在幀布局里面套一個線性布局,其中線性布局里面放內容,其次再在幀布局的頂部和底部分別放兩張漸變圖片不就好了。我想說的是,這么做雖然也可以,但是卻為了實現效果而加入頁面嵌套,導致頁面多重繪制,簡單頁面還好,對于復雜點的頁面,可能會影響頁面性能甚至卡頓。
所以,我的實現思路就是,直接重寫線性布局,在該布局繪制的時候,分別在頂部和底部畫上漸變圖片,而且為了實現漸變線的可定制性,圖片部分也是使用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;
}
}