创建自定义视图

时间:2013-07-26 14:31:13

标签: android android-view android-custom-view

我正在努力实现使用自定义形状(几乎是矩形)创建视图的效果。

这是我试图做的事情:

public class CustomHeaderview extends View {

    public CustomHeaderview(Context context) {
        super(context);
    }

    public CustomHeaderview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomHeaderview(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    Paint paint = new Paint();

    @Override
public void draw(Canvas canvas) {
    paint.setColor(Color.GRAY);
    paint.setStyle(Style.FILL);

    Path wallpath = new Path();
    wallpath.reset(); // only needed when reusing this path for a new build
    wallpath.moveTo(100, 100); // used for first point
    wallpath.lineTo(100, 200);
    wallpath.lineTo(200, 200);
    wallpath.lineTo(150, 100);
    wallpath.lineTo(100, 100);// there is a setLastPoint action but i found it not to work as expected

    canvas.drawPath(wallpath, paint);
    super.draw(canvas);
}

}

和XML:

<CustomHeaderview
            android:layout_width="152dp"
            android:layout_height="152dp" />

修改 感谢德米特里,它现在完美无缺!

1 个答案:

答案 0 :(得分:0)

您为矩形提供了精美的坐标:

x1: 100
y1: 100
x2: 100
y2: 120

所以,你得到的宽度为0的矩形,这就是为什么它是不可见的。