Android 使用xml定义制作三角形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2517589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:09:10  来源:igfitidea点击:

Making a triangle shape using xml definitions?

androidxml

提问by user291701

Is there a way that I can specify a triangle shape in an xml file?

有没有办法在 xml 文件中指定三角形?

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="triangle">
  <stroke android:width="1dip" android:color="#FFF" />
  <solid android:color="#FFF" />
</shape>

can we do this with a path shape or something? I just need an equilateral triangle.

我们可以用路径形状或其他东西来做到这一点吗?我只需要一个等边三角形。

Thanks

谢谢

回答by Jacek Milewski

In this postI describe how to do it. And here is the XML defining triangle:

这篇文章中,我描述了如何做到这一点。这是 XML 定义三角形:

<?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="-40%"
            android:pivotY="87%" >
            <shape
                android:shape="rectangle" >
                <stroke android:color="@color/transparent" android:width="10dp"/>
                <solid
                    android:color="@color/your_color_here" />
            </shape>
        </rotate>
    </item>
</layer-list>

Refer to my post if something is unclear or you need explanation how it is built. It is rotated an cutout rectangle :) it is very smart and well working solution.

如果有不清楚的地方或者您需要解释它是如何构建的,请参阅我的帖子。它旋转了一个切口矩形 :) 这是一个非常智能且运行良好的解决方案。

EDIT: to create an arrow pointing like --> use:

编辑:创建一个箭头指向像 --> 使用:

...
android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="13%"
android:pivotY="-40%" >
...

And to create an arrow pointing like <-- use:

并创建一个指向 <-- 的箭头,使用:

android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="87%"
android:pivotY="140%" >

回答by Elhanan Mishraky

<TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="▼"/>

You can get heremore options.

您可以在这里获得更多选择。

回答by Phan Van Linh

You can use vectorto make triangle like this

你可以vector用来制作这样的三角形

ic_triangle_right.xml

ic_triangle_right.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:pathData="M0,12l0,12 11.5,-5.7c6.3,-3.2 11.5,-6 11.5,-6.3 0,-0.3 -5.2,-3.1 -11.5,-6.3l-11.5,-5.7 0,12z"
        android:strokeColor="#00000000"
        android:fillColor="#000000"/>
</vector>

Then use it like

然后像这样使用它

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_triangle_right"
    />

For change the color and direction, use android:tintand android:rotation

要更改颜色和方向,请使用android:tintandroid:rotation

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_triangle_right"
    android:rotation="180" // change direction
    android:tint="#00f" // change color
    />

Result

结果

enter image description here

在此处输入图片说明

For change the shape of vector, you can change the width/height of vector. Example change width to 10dp

要更改矢量的形状,您可以更改矢量的宽度/高度。示例将宽度更改为 10dp

<vector 
        android:width="10dp"
        android:height="24dp"
        >
       ...
</vector>

enter image description here

在此处输入图片说明

回答by Oliver Metz

You can use vector drawables.

您可以使用矢量可绘制对象

If your minimum API is lower than 21, Android Studio automatically creates PNG bitmaps for those lower versions at build time (see Vector Asset Studio). If you use the support library, Android even manages "real vectors" down to API 7 (more on that in the update of this post at the bottom).

如果您的最低 API 低于 21,Android Studio 会在构建时自动为这些较低版本创建 PNG 位图(请参阅Vector Asset Studio)。如果您使用支持库,Android 甚至可以管理低至 API 7 的“真实向量”(更多信息请参见底部这篇文章的更新)。

A red upwards pointing triangle would be:

一个红色的向上指三角形将是:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="100" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#FF0000"
            android:pathData="m 50,0 l 50,100 -100,0 z" />
    </group>
</vector>

Add it to your layout and remember to set clipChildren="false" if you rotate the triangle.

将其添加到您的布局中,并记住在旋转三角形时设置 clipChildren="false"。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false">

    <ImageView
        android:layout_width="130dp"
        android:layout_height="100dp"
        android:rotation="0"
        android:layout_centerInParent="true"
        android:background="@drawable/triangle"/>

</RelativeLayout>

enter image description here

在此处输入图片说明

Change the size (width/height) of the triangle by setting the Views layout_width/layout_height attributes. This way you can also get an eqilateral triagle if you do the math correct.

通过设置视图 layout_width/layout_height 属性来更改三角形的大小(宽度/高度)。通过这种方式,如果你的数学正确,你也可以获得一个等边三角形。

UPDATE 25.11.2017

2017 年 11 月 25 日更新

If you use the support library you can use real vectors (instead if bitmap creation) as far back as API 7. Simply add:

如果您使用支持库,则可以早在 API 7 时使用实向量(而不是创建位图)。只需添加:

vectorDrawables.useSupportLibrary = true

do your defaultConfigin your module's build.gradle.

defaultConfig在你的模块的 build.gradle 中做你的。

Then set the (vector xml) drawable like this:

然后像这样设置(vector xml)drawable:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/triangle" />

Everything is documented very nicely on the Vector Asset Studiopage.

Vector Asset Studio页面上的所有内容都记录得非常好。

Ever since this feature I've been working entirely without bitmaps in terms of icons. This also reduces APK size quite a bit.

自从有了这个功能,我就一直在工作,完全没有图标方面的位图。这也大大减少了 APK 的大小。

回答by Peter

I would definetely go for implementing a View in this case:

在这种情况下,我肯定会去实现一个视图:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class TriangleShapeView extends View {

    public TriangleShapeView(Context context) {
        super(context);
    }

    public TriangleShapeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TriangleShapeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int w = getWidth() / 2;

        Path path = new Path();
        path.moveTo( w, 0);
        path.lineTo( 2 * w , 0);
        path.lineTo( 2 * w , w);
        path.lineTo( w , 0);
        path.close();

        Paint p = new Paint();
        p.setColor( Color.RED );

        canvas.drawPath(path, p);
    }
}

Make use of it in your layouts as follows:

在您的布局中使用它,如下所示:

<TriangleShapeView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff487fff">
</TriangleShapeView>

Using this implementation will give you the following result:

使用此实现将为您提供以下结果:

enter image description here

在此处输入图片说明

回答by senechaux

The solution of Jacek Milewskiworks for me and, based on his solution, if you need and inversed triangle you can use this:

Jacek Milewski解决方案对我有用,根据他的解决方案,如果您需要倒三角形,您可以使用它:

<?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="135%" 
            android:pivotY="15%">
            <shape android:shape="rectangle">    
                <solid android:color="@color/aquamarine" />
            </shape>
        </rotate>
    </item>
</layer-list>

回答by zed

See answer here: Custom arrows without image: Android

在此处查看答案: 没有图像的自定义箭头:Android

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="32dp"
        android:height="24dp"
        android:viewportWidth="32.0"
        android:viewportHeight="24.0">
    <path android:fillColor="#e4e4e8"
          android:pathData="M0 0 h32 l-16 24 Z"/>
</vector>

arrow

箭

回答by Ahmed Ghoneim

May I help you withoutusing XML ?

我可以在使用 XML 的情况下帮助您吗?



Simply,

简单地,

Custom Layout ( Slice ) :

自定义布局(切片):

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;

public class Slice extends View {

    Paint mPaint;

    Path mPath;

    public enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    public Slice(Context context) {
        super(context);
        create();
    }

    public Slice(Context context, AttributeSet attrs) {
        super(context, attrs);
        create();
    }

    public void setColor(int color) {
        mPaint.setColor(color);
        invalidate();
    }

    private void create() {
        mPaint = new Paint();
        mPaint.setStyle(Style.FILL);
        mPaint.setColor(Color.RED);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPath = calculate(Direction.SOUTH);
        canvas.drawPath(mPath, mPaint);
    }

    private Path calculate(Direction direction) {
        Point p1 = new Point();
        p1.x = 0;
        p1.y = 0;

        Point p2 = null, p3 = null;

        int width = getWidth();

        if (direction == Direction.NORTH) {
            p2 = new Point(p1.x + width, p1.y);
            p3 = new Point(p1.x + (width / 2), p1.y - width);
        } else if (direction == Direction.SOUTH) {
            p2 = new Point(p1.x + width, p1.y);
            p3 = new Point(p1.x + (width / 2), p1.y + width);
        } else if (direction == Direction.EAST) {
            p2 = new Point(p1.x, p1.y + width);
            p3 = new Point(p1.x - width, p1.y + (width / 2));
        } else if (direction == Direction.WEST) {
            p2 = new Point(p1.x, p1.y + width);
            p3 = new Point(p1.x + width, p1.y + (width / 2));
        }

        Path path = new Path();
        path.moveTo(p1.x, p1.y);
        path.lineTo(p2.x, p2.y);
        path.lineTo(p3.x, p3.y);

        return path;
    }
}

Your Activity ( Example ) :

您的活动(示例):

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

public class Layout extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Slice mySlice = new Slice(getApplicationContext());
        mySlice.setBackgroundColor(Color.WHITE);
        setContentView(mySlice, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    }
}

Working Example :

工作示例:

enter image description here

在此处输入图片说明



Another absolutely simple Calculatefunction you may interested in ..

Calculate您可能感兴趣的另一个绝对简单的功能..

private Path Calculate(Point A, Point B, Point C) {
    Path Pencil = new Path();
    Pencil.moveTo(A.x, A.y);
    Pencil.lineTo(B.x, B.y);
    Pencil.lineTo(C.x, C.y);
    return Pencil;
}

回答by Zygi

Using vector drawable:

使用矢量可绘制:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
   android:width="24dp"
   android:height="24dp"
   android:viewportWidth="24.0"
   android:viewportHeight="24.0">
   <path
        android:pathData="M0,0 L24,0 L0,24 z"
        android:strokeColor="@color/color"
        android:fillColor="@color/color"/>
</vector>

enter image description here

在此处输入图片说明

回答by Chong Chern Dong

For those who want a right triangle arrow, here you go:

对于那些想要直角三角形箭头的人,这里是:

STEP 1:Create a drawable XML file, copy and paste the following XML content into your drawable XML. (Please be informed that you can use any name for your drawable XML file. For my case, I name it "v_right_arrow")

第 1创建一个可绘制的 XML 文件,将以下 XML 内容复制并粘贴到您的可绘制 XML 中。(请注意,您可以为可绘制 XML 文件使用任何名称。就我而言,我将其命名为“v_right_arrow”)

<?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="15%"
            android:pivotY="-36%" >
            <shape
                android:shape="rectangle"  >
                <stroke android:color="@android:color/transparent" android:width="1dp"/>
                <solid
                    android:color="#000000"  />
            </shape>
        </rotate>
    </item>
</layer-list>

STEP 2:In your layout's XML, create a View and bind its background to the drawable XML that you have just created in STEP 1. For my case, I bind v_right_arrow to my View's background property.

第 2 步:在布局的 XML 中,创建一个视图并将其背景绑定到您刚刚在第1步中创建的可绘制 XML 。就我而言,我将 v_right_arrow 绑定到我的视图的背景属性。

<View
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@drawable/v_right_arrow">
</View>

Sample output:

示例输出:

enter image description here

在此处输入图片说明

Hope this helps, good luck!

希望这有帮助,祝你好运!