Material Lollipop上的半透明渐变状态栏显示在Material Design中

问题描述 投票:11回答:1

我想做像这样的Gradient status bar

对于Android 5.0及更高版本?

我该如何实现呢?我在StackOverFlow或Android开发者网站上找不到任何解决方案。

我建议我可以使状态栏透明,并在状态栏下绘制渐变可绘制。但是问题很少。

第一个问题是形状可绘制的通常渐变不支持材料设计规范http://www.google.com/design/spec/style/imagery.html Material Design gradient

第二个问题是我无法通过android:fitsSystemWindows="true"将地图片段放到窗口中。

android material-design android-appbarlayout
1个回答
0
投票

给出与Material Design网站上显示的大致相同的图的公式为:

y = 3/(4*(x+0.5)) - 0.5

我已经尝试了几种通过Canvas绘制双曲面渐变的方法,并找到了最快的解决方案。

public class HyperbolaGradientDrawable extends Drawable {

private static final int ALPHA_DEFAULT = (int) (0.6f * 255);

private int mAlpha = ALPHA_DEFAULT;
private int mColor;
private Rect  mBmpRect = new Rect();
private int[] mColors  = new int[0];
private Bitmap mBmp;

@Override
public void draw(Canvas canvas) {
    Rect bounds = getBounds();
    if (mColors.length != bounds.height()) {
        int alpha;
        float y, alphaRelative;
        mColors = new int[bounds.height()];
        for (int i = 0; i < bounds.height(); i++) {
            y = ((float) i) / bounds.height();
            // this function gives approximately 0.5 of the bearing alpha at 3/10ths closed to the darker end
            alphaRelative = 3 / (4 * (y + 0.5f)) - 0.5f;
            alpha = (int) (alphaRelative * mAlpha);
            mColors[i] = alpha << 24 | mColor;
        }
        mBmp = Bitmap.createBitmap(mColors, 1, bounds.height(), Bitmap.Config.ARGB_8888);
        mBmpRect.set(0, 0, 1, bounds.height());
    }
    canvas.drawBitmap(mBmp, mBmpRect, bounds, null);
}

public void setColor(int color) {
    // remove alpha chanel
    mColor = color & 0x00FFFFFF;
}

@Override
public void setAlpha(int alpha) {
    mAlpha = alpha;
}

@Override
public void setColorFilter(ColorFilter colorFilter) {

}

@Override
public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
}
}

我知道谷歌建议不要在draw方法中创建新对象,但它比通过Canvas逐行绘制更快。

您可以查看demo project中几种方式的比较

© www.soinside.com 2019 - 2024. All rights reserved.