尝试绘制一个按钮:如何设置描边颜色并将渐变“对齐”到底部,而不知道高度是多少?

11

我正在编写一个程序创建按钮。它是圆角的,有渐变背景,功能正常且外观漂亮,但我无法做到以下两点:

  1. 设置一个给定颜色的1像素描边。我尝试使用getPaint().setStroke(),但无法弄清如何设置描边颜色。我应该怎么做?
  2. 将渐变对齐到按钮底部,无论其高度如何。这可能吗?

供参考,这是我正在使用的代码:

Button btn = new Button(context);
btn.setPadding(7, 3, 7, 5);
btn.setTextColor(text_color);

// Create a gradient for the button. Height is hardcoded to 30 (I don't know the height beforehand). 
// I wish I could set the gradient aligned to the bottom of the button.
final Shader shader = new LinearGradient(0, 0, 0, 30,
    new int[] { color_1, color_2 },
    null, Shader.TileMode.MIRROR);

float[] roundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }
ShapeDrawable normal = new ShapeDrawable(new RoundRectShape(roundedCorner, null, null));
normal.getPaint().setShader(shader);
normal.setPadding(7, 3, 7, 5);

// Create a state list (I suppressed settings for pressed).
StateListDrawable state_list = new StateListDrawable();
state_list.addState(new int[] { }, normal);

btn.setBackgroundDrawable(state_list);
3个回答

22

就您的第一个问题而言,我也遇到了同样的困难,看起来在Drawables本身(我使用的是ShapeDrawable)或Paint类中没有合适的方法。但是,我可以通过扩展ShapeDrawable并重写绘制方法(如下所示)来实现相同的结果:

public class CustomBorderDrawable extends ShapeDrawable {
    private Paint fillpaint, strokepaint;
    private static final int WIDTH = 3; 

    public CustomBorderDrawable(Shape s) {
        super(s);
        fillpaint = this.getPaint();
        strokepaint = new Paint(fillpaint);
        strokepaint.setStyle(Paint.Style.STROKE);
        strokepaint.setStrokeWidth(WIDTH);
        strokepaint.setARGB(255, 0, 0, 0);
    }

    @Override
    protected void onDraw(Shape shape, Canvas canvas, Paint fillpaint) {
        shape.draw(canvas, fillpaint);
        shape.draw(canvas, strokepaint);
    }

    public void setFillColour(int c){
        fillpaint.setColor(c);
    }
}

这个几乎可以工作,但描边被裁剪了。此链接有更多详情:http://www.betaful.com/2012/01/programmatic-shapes-in-android/ - mxcl
1
以上链接已失效。这是更新后的链接: http://betaful.com/post/82668809883/programmatic-shapes-in-android - Shams Shafiq
@ShamsShafiq,@Stev_k@moraes,我尝试使用你们的方法以及betauful.com上的答案来编写一个可以动态创建带有圆角边框的程序...它很好用,但是它也会在视图外创建一个边缘。我得到的视图链接如下:https://drive.google.com/file/d/0BwkVxZWl7VcETlIySV82NC1sV2s/view?usp=sharing,请帮我去掉灰色边缘。 - Reprator

8
您可以使用 GradientDrawable 并调用 setStroke(3, Color.WHITE) 方法。如需制作圆角,请使用以下方法:
setShape(GradientDrawable.RECTANGLE);
setCornerRadii(new float[]{2,2,2,2,2,2,2,2});

1
尝试这个...在drawable中创建一个新的xml文件,并将其设置在您想要的位置..!
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#e1e1e1" />

    <stroke
        android:width="2dp"
        android:color="#808080" />

    <corners android:radius="10dp" />

    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

</shape>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接