簡體   English   中英

以編程方式創建帶有圓角和漸變背景的按鈕

[英]Create button with rounded corners and gradient background programmatically

我必須根據用戶繪制按鈕。 這些按鈕必須是圓角和漸變背景。

為了實現這個結果,這是我創建按鈕的代碼:

        ImageButton btn = new ImageButton(this);
        btn.setBackgroundDrawable(null);
        GradientDrawable gradientNormal = new GradientDrawable(Orientation.BOTTOM_TOP,
                new int[] { cc.getColorSelector()[1], cc.getColorSelector()[0] });
        GradientDrawable gradientPressed = new GradientDrawable(Orientation.BOTTOM_TOP,
                new int[] { cc.getColorSelector()[0], cc.getColorSelector()[1] });
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[] { android.R.attr.state_pressed }, gradientPressed);
        stateListDrawable.addState(new int[] {}, gradientNormal);
        RoundRectShape rect = new RoundRectShape(new float[] { 30, 30, 30,
                30, 30, 30, 30, 30 }, null, null);
        ShapeDrawable bg = new ShapeDrawable(rect);

cc.getColorSelector() 只返回整數顏色。

現在我需要將 ShapeDrawable 的形狀與 StateListDrawable 的顏色合並,以便有一個可以用作按鈕背景的可繪制對象。

請問我該怎么做?

使用此代碼

    final Button btn = (Button) v.findViewById(R.id.btn);
    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(0, 0, arBtn.getWidth(), 0,
                    new int[]{
                            Color.parseColor("#4B94FF"),
                            Color.parseColor("#578FFA"),
                            Color.parseColor("#7881EE"),
                            Color.parseColor("#AE6ADA"),
                            Color.parseColor("#EF4FC2")}, //substitute the correct colors for these
                    new float[]{
                            0, 0.125f, 0.375f, 0.687f, 1},
                    Shader.TileMode.REPEAT);
            return lg;
        }
    };
    PaintDrawable p = new PaintDrawable();
    p.setShape(new RoundRectShape(new float[] { 30, 30, 30,
            30, 30, 30, 30, 30 }, null, null));
    p.setShaderFactory(sf);
    btn.setBackground((Drawable) p);

僅漸變作為背景

您可以使用GradientDrawable實現此結果,如下所示:

button.background = getRoundedTintedDrawable(Color.BLUE) // change it to any color
.
.
.

private fun getRoundedTintedDrawable(color: Int): Drawable {
    GradientDrawable().run {
        // set rounded corners
        cornerRadius = DEFAULT_RADIUS // in dp

        // set the gradient type
        gradientType = GradientDrawable.LINEAR_GRADIENT // there is radial, oval, etc..

        // set gradient orientation
        orientation = GradientDrawable.Orientation.LEFT_RIGHT // right to left, top to bottom, etc...

        // gradient colors 
        colors = intArrayOf(Color.BLACK, Color.BLUE) // change to any array of colors

        return this
    }
}

使用 getRoundedTintedDrawable 單擊事件效果

如果你想有任何點擊事件效果,你需要使用StateListDrawable和 View 狀態和上面的getRoundedTintedDrawable方法:

button.background = setColorSelection(Color.BLUE) // change it to any color
.
.
.
private fun setColorSelection(color: Int): StateListDrawable {
    StateListDrawable().run {
        setExitFadeDuration(PRESS_DURATION)
        addState(ViewState.DISABLED.state, getRoundedTintedDrawable(getColorWithAlpha(color)))
        addState(ViewState.PRESSED.state, getRoundedTintedDrawable(getDarkerColor(color)))
        addState(ViewState.DEFAULT.state, getRoundedTintedDrawable(color))
        return this
    }
}

這是視圖狀態抽象枚舉:

/**
* Possible view states list
* **/
internal enum class ViewState (val state: IntArray) {
   PRESSED (intArrayOf(android.R.attr.state_pressed)),
   FOCUSED (intArrayOf(android.R.attr.state_focused)),
   DISABLED (intArrayOf(-android.R.attr.state_enabled)),
   CHECKED (intArrayOf(android.R.attr.state_checked)),
   DEFAULT (intArrayOf())
}

這是顏色計算器以獲得更暗和更透明的顏色:

  /**
 * @return a [Color] darker than [color]
 * **/
private fun getDarkerColor(color: Int): Int{
    val hsv = FloatArray(3)
    Color.colorToHSV(color, hsv)
    hsv[2] *= BRIGHTNESS_REDUCTION // change the brightness of the color
    return Color.HSVToColor(hsv)
}

// @return a [Color] more translucent than [color]
private fun getColorWithAlpha(color: Int, ratio: Float = ALPHA_FADE_DISABLE): Int {
    return Color.argb((Color.alpha(color) * ratio).roundToInt(), Color.red(color), Color.green(color), Color.blue(color))
}

我們可以設置一些默認值來幫助我們更改效果與按鈕的交互方式。

private companion object {
    const val BRIGHTNESS_REDUCTION = 0.8f
    const val PRESS_DURATION = 200 //ms
    const val ALPHA_FADE_DISABLE = 0.4f
    const val DEFAULT_COLOR = Color.GRAY
    const val DEFAULT_RADIUS = 10f // dp
}

希望有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM