如何以编程方式在Android中的按钮周围绘制平滑笔触?

时间:2011-10-30 20:48:31

标签: android button android-layout paint

我试图在渐变填充按钮周围绘制平滑的抗锯齿笔划,但角落变得非常难看。这是我的代码:

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;

public class StrokeShapeDrawable extends ShapeDrawable {
    Paint fillpaint;
    Paint strokepaint;
    private static final int WIDTH = 1;

    public StrokeShapeDrawable(Shape s) {
        super(s);
        fillpaint = this.getPaint();
        strokepaint = new Paint(fillpaint);
        strokepaint.setAntiAlias(true);
        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);
    }
}

按钮创建:

    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(0, 0, 0, mLoginBtn.getHeight(),
                new int[] { 
                    0xfff6f6f6, 
                    0xffd2d3d5, 
                    0xffc0c1c4, 
                    0xffc0c1c4},
                new float[] {
                    0, 0.45f, 0.55f, 1 },
                Shader.TileMode.REPEAT);
             return lg;
        }
    };

    float[] roundedCorner = new float[] {15, 15, 15, 15, 15, 15, 15, 15};
    StrokeShapeDrawable b = new StrokeShapeDrawable(new RoundRectShape(roundedCorner, null, null));
    b.setShaderFactory(sf);
    mLoginBtn.setBackgroundDrawable((Drawable)b);

我的按钮如下所示:

Button

不是很好,有人有什么想法吗?

此外,我不想使用XML文件,因为我不确定是否可以实现两个渐变,每个按钮有50个precent,而不使用dp指定渐变位置(因为我想要50-50渐变)。

谢谢!

1 个答案:

答案 0 :(得分:1)

这让我觉得这是一种过于复杂的方式来实现相对简单的事情。我本来会用nine-patch drawable代替它们 - 它们非常适合你的任务。