我发现在 XML 中处理旋转的正方形对于创建我想要的三角形有点不可预测。我制作了一个自定义视图类,它根据您给它的宽度和高度绘制三角形:
public class TriangleView extends View {
public static final int UP = 0;
public static final int DOWN = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
private int colour;
private int direction;
private Paint paint;
public int getColour() {return colour;}
public int getDirection() {return direction;}
public void setColour(int colour) {
this.colour = colour;
invalidate();
requestLayout();
}
public void setDirection(int direction) {
this.direction = direction;
invalidate();
requestLayout();
}
public TriangleView(Context context, AttributeSet attrs) {
super(context, attrs);
initAttributes(attrs);
setupPaint();
}
private void initAttributes(AttributeSet attrs) {
TypedArray attrArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.TriangleView, 0, 0);
try {
colour = attrArray.getColor(R.styleable.TriangleView_triangleColor, Color.BLACK);
direction = attrArray.getInt(R.styleable.TriangleView_direction, UP);
} finally {
attrArray.recycle();
}
}
private void setupPaint() {
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(colour);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(getTrianglePath(), paint);
}
protected Path getTrianglePath() {
Point p1, p2, p3;
switch (direction) {
case UP:
p1 = new Point(getPaddingLeft(), getHeight() - getPaddingBottom());
p2 = new Point(getWidth() - getPaddingRight(), p1.y);
p3 = new Point((getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft() , getPaddingTop());
break;
case DOWN:
default:
p1 = new Point(getPaddingLeft(), getPaddingTop());
p2 = new Point(getWidth() - getPaddingRight(), p1.y);
p3 = new Point((getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft(), getHeight() - getPaddingBottom());
break;
}
Path path = new Path();
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
return path;
}
}
您还需要将以下内容添加到您的 res/values/attrs.xml 文件中:
<declare-styleable name="TriangleView">
<attr name="triangleColor" format="color" />
<attr name="direction" format="enum">
<enum name="up" value="0" />
<enum name="down" value="1" />
<enum name="left" value="2" />
<enum name="right" value="3" />
</attr>
</declare-styleable>
然后您可以在您的布局 xml 中任何您想绘制三角形的地方使用它:
<com.mypackagename.TriangleView
android:id="@+id/loseScreen"
android:layout_width="200dp"
android:layout_height="200dp"
app:triangleColor="@color/loseBackground"
app:direction="up"
android:padding="10dp"/>
记得将应用命名空间添加到您的 xml 布局中:
xmlns:app="http://schemas.android.com/apk/res-auto"