您可以创建一个自定义视图类。
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。
请注意,这不是复制/粘贴代码。您将需要对其进行调整,但它应该让您领先一步。祝你好运。