如何在Android XML中绘制直角三角形形状

3

在此输入图片描述

如何使用xml在Android中创建形状?


1
不要在XML中做这件事,这是浪费时间,相反使用Canvas API进行绘制。 - pskink
3个回答

6

更新,现在是一个直角三角形
这一定会有效
enter image description here1

  1. 这段代码将生成一个向左的三角形,就像上面的照片一样。


<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate
            android:fromDegrees="52"
            android:toDegrees="45"
            android:pivotX="-45%"
            android:pivotY="90%" >

            <shape
                android:shape="rectangle" >

                <solid
                    android:color="@color/colorPrimary"/>
            </shape>
        </rotate>
    </item>
</layer-list>

2 enter image description here

  1. 这段代码将会生成一个类似上面图片的右侧三角形。


<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate
            android:fromDegrees="-50"
            android:toDegrees="45"
            android:pivotX="140%"
            android:pivotY="90%" >

            <shape
                android:shape="rectangle" >

                <solid
                    android:color="@color/colorPrimary"/>
            </shape>
        </rotate>
    </item>
</layer-list>

这个不起作用。它是一个等边三角形。我想要一个直角的。 - Pedro Simões
请问您能否解释一下登录背后的原理?解决方案很完美,但我不知道我们是如何实现的。 - Nishchay Zacariah
1
@NishchayZacariah 由于三角形不是默认形状,因此我们首先将矩形旋转成菱形或钻石形状,使用 fromDegreestoDegrees,然后使用 pivotXpivotY 将形状移出视图以使所需的形状区域可见,即三角形。因此,它始终是一个矩形,但在视觉上呈现为三角形,因为其他部分超出了视图边界并且不可见。要将矩形向右或向左旋转成菱形/风筝形状,我们使用 fromDegreestoDegrees,然后相应地移动它。 - Lalit Fauzdar
明白了,Lalit。非常感谢你。 - Nishchay Zacariah

2
请尝试这个。
同时,也请查看我的另一个回答如何在Android Studio中创建矢量图形enter image description here
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="108dp"
    android:height="113dp"
    android:viewportWidth="108"
    android:viewportHeight="113">
  <path
      android:pathData="M2.423,111.534L105.599,110.724L1.032,3.022L2.423,111.534Z"
      android:strokeWidth="2"
      android:fillColor="#ffffff"
      android:strokeColor="#000000"/>
</vector>

enter image description here

 <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="119dp"
    android:height="126dp"
    android:viewportWidth="119"
    android:viewportHeight="126">
  <path
      android:strokeWidth="1"
      android:pathData="M117.632,124.928L1.686,125.144L118.003,2.092L117.632,124.928Z"
      android:fillColor="#ffffff"
      android:strokeColor="#000000"/>
</vector>

-3
使用此代码可创建行。
<View
    android:id="@+id/view"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/textView4"
    android:layout_marginTop="210dp"
    android:background="@color/cardview_dark_background"/>

你已经掌握了画线,画三角形也不是什么大问题了。


1
尽管这个答案画了一条线,但没有说明如何旋转这些线并将它们对齐。 - Tim Kist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接