以编程方式创建带圆角和渐变背景的按钮

时间:2013-10-12 10:17:22

标签: android android-button android-drawable

我必须根据用户绘制按钮。 这些按钮必须是圆角和渐变背景。

要实现此结果,这是我创建按钮的代码:

        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的颜色合并,以便有一个drawable我可以用作我按钮的背景。

我该怎么办?

2 个答案:

答案 0 :(得分:0)

使用此代码

    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);

答案 1 :(得分:0)

  

仅以梯度为背景

您可以使用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和上面的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
    }
}

这是View状态抽象枚举:

/**
* 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
}

希望有帮助:)