0

I have an xml layout that has 3 input boxes and a 'generate' button. When the user puts in there values there I'd like to draw a triangle underneath it

I know how to create a new view and go to it, but I'm not sure how to draw it on the same view being that I'm working with an xml view.

Below is a screenshot of what I want to do. Thank you

http://i.stack.imgur.com/9oBJV.png

4

2 回答 2

1

您可以创建一个自定义视图类。

class Triangle extends View {

      private int vertexA, vertexB, vertexC;

      public Triangle(Context ctx){
          this(ctx,null);
      }

      public Triangle(Context ctx, AttributeSet attrs){
          this(ctx,attrs,0);
      }


      public Triangle(Context ctx, AttributeSet attrs, int defStyle){
          super(ctx,attrs,defStyle);
      }


      public void setSides(int a, int b, int c){
          this.vertexA = a;
          this.vertexB = b;
          this.vertexC = c;
          this.invalidate();
      }

      @Override
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

          // Try for a width based on our minimum
          int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
          int w = resolveSizeAndState(minw, widthMeasureSpec, 1);

          // Whatever the width ends up being, ask for a height that would let the triangle
         // get as big as it can
          int minh = MeasureSpec.getSize(w) - (int)mTextWidth + getPaddingBottom() + getPaddingTop();
          int h = resolveSizeAndState(MeasureSpec.getSize(w) - (int)mTextWidth, heightMeasureSpec, 0);

          setMeasuredDimension(w, h);
      }

      @Override
      protected void onDraw(Canvas canvas) {

          super.onDraw(canvas);

          Paint paint = new Paint();
          Path path = new Path();

          paint.setStyle(Paint.Style.FILL);
          paint.setColor(Color.TRANSPARENT);

          c.drawPaint(paint);

          // start the path at the "origin"
          path.MoveTo(10,10); // origin
          // add a line for side A
          path.lineTo(10,this.vertexA);
          // add a line for side B
          path.lineTo(this.vertexB,10);
          // close the path to draw the hypotenuse
          path.close();

          paint.setStrokeWidth(3);
          paint.setPathEffect(null);
          paint.setColor(Color.BLACK);
          paint.setStyle(Paint.Style.STROKE);

          c.drawPath(path, paint);

     } 

}

请注意,我已经硬编码了原点(左下角 - 直角)并且只绘制了两条边,因为斜边是由闭合路径绘制的(这样可以节省任何额外的数学运算)。您需要使用 onMeasure 并根据需要缩放三角形。像这样的东西:

path.lineTo(10, this.vertexA * yScale);
path.lineTo(this.vertexB * xScale ,10);

您的活动应该检查 3 个值确实代表直角三角形的边,然后调用 setSides()。我已经添加了所有 3 面,尽管我们只使用 a 和 b。如果您愿意,可以删除 c。

请注意,这不是复制/粘贴代码。您将需要对其进行调整,但它应该让您领先一步。祝你好运。

于 2013-01-01T19:10:10.113 回答
0

只需将您的自定义视图放入按钮下方的布局中。要使用的确切 xml 取决于您的顶级视图容器的类型(可能是 a RelativeLayout)。

要使其一开始不可见,您可以将其可见性设置为INVISIBLE。当它应该出现时,将可见性设置为VISIBLE

于 2013-01-01T19:04:30.093 回答