Расширяем нарисованный треугольник - Android
У меня есть этот код в отрисовке, которая строит треугольник. Однако я думаю, что гипотенуза слишком длинна по сравнению с шириной треугольника. Я бы хотел, чтобы это было похоже на равносторонний треугольник. Как мне это сделать? Спасибо!
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<rotate
android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="-45%"
android:pivotY="100%" >
<shape
android:shape="rectangle"
>
<solid
android:color="@color/loseBackground" />
</shape>
</rotate>
</item>
</layer-list>
Я сделал этот код на фоне кнопки.
<Button
android:id="@+id/loseScreen"
android:layout_width="200dp"
android:layout_height="200dp"
android:rotation="90"
android:visibility="invisible"
android:layout_x="140dp"
android:layout_y="120dp"
android:background="@drawable/triangle_shape" />
2 ответа
Я просто решил это с помощью этого:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="▼"/>
Это работает довольно хорошо. Я мог бы изменить его, если найду лучшее решение.
Я обнаружил, что смешивание с повернутыми квадратами в 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"