android创建自定义形状布局

时间:2014-09-05 06:48:40

标签: android layout shape

我需要创建ViewGroup自定义形状。它可能是FrameLayout。它应该看起来像enter image description here

它必须是ViewGroup因为我需要在里面添加文本或图像。我怎么能这样做?非常感谢。

1 个答案:

答案 0 :(得分:1)

创建自定义多边形形状有一个很好的tutorial here。这是一个相当漫长的过程,但你会到达那里。简而言之,您必须为自定义View创建自定义XML属性。

真正的魔力在于:

    @Override
    protected void onDraw(Canvas canvas) {
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        int x = (measuredWidth/2)  ;
        int y = (measuredHeight/2) ;
        int radius = Math.min(x,y) ;

        if (sides < 3) return;

        float a = (float) (Math.PI * 2)/sides;
        int workingRadius = radius;
        polyPath.reset();

        // The poly is created as a shape in a path.
        // If there is a hole in the poly, draw a 2nd shape inset from the first
        for(int j = 0; j < ((fillPercent < 100) ? 2 : 1) ; j++){
            polyPath.moveTo(workingRadius,0);
            for (int i = 1; i < sides; i++) {
                polyPath.lineTo((float)(workingRadius*Math.cos(a*i)),
                (float)(workingRadius*Math.sin(a*i)));
            }
            polyPath.close();

            workingRadius -= radius * fillPercent;
            a = -a;
        }

        canvas.save();
        canvas.translate(x, y);
        canvas.rotate(startAngle);
        canvas.drawPath(polyPath, fillPaint);

        canvas.restore();

        if(showInscribedCircle){
            canvas.drawCircle(x,y,radius, inscribedCirclePaint);
        }
        super.onDraw(canvas);
    }