如何在Android的xml中制作一个具有两种颜色的可绘制矩形?

3

我想在Android中使用XML制作类似于这样的东西。我使用了45度角的渐变实现了类似的效果,但我不想要渐变,而是像这样的纯色。非常感谢任何建议。提前致谢。

这就是我想要使用XML创建的东西。

enter image description here

我需要很多这样的内容,因此无法在drawable文件夹中加载位图。]1

4个回答

0

以下答案是毫不掩饰地从这里复制过来的 如何在Android中制作渐变背景

尝试使用以下代码:

<gradient
    android:angle="90"   //you need to change angle as per your needs (270 might work in your case)
    android:centerColor="#555994"  //try playing with colors of start, center and End colors to get desired result. also try removing some.
    android:endColor="#b5b6d2"
    android:startColor="#555994"
    android:type="linear" />

<corners 
    android:radius="0dp"/>

为了使用上述代码,您需要创建一个可绘制的 .xml 文件,并将上述代码复制粘贴到该文件中。
谢谢。

这将帮助您根据需要设置视图的背景。 - karan

0

我不知道在XML中是否可能。 在Java中,一种可能的方法是创建一个Shape并用它构建一个ShapeDrawable。

TwoTrianglesDrawable.java

public class TwoTrianglesDrawable extends ShapeDrawable {

    public TwoTrianglesDrawable(){
        super();
        setShape(new TwoTrianglesShape());
    }

    private class TwoTrianglesShape extends Shape {

        @Override
        public void draw(Canvas canvas, Paint paint) {

            Path path = new Path();
            path.setFillType(Path.FillType.INVERSE_EVEN_ODD);
            Path path1 = new Path();
            path1.setFillType(Path.FillType.INVERSE_EVEN_ODD);

            paint.setStrokeWidth(0);
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);

            paint.setColor(Color.YELLOW);

            Point a = new Point(0, 0);
            Point b = new Point(0, (int) getHeight());
            Point c = new Point((int)getWidth(), (int)getHeight());

            path.moveTo(a.x, a.y);
            path.lineTo(b.x, b.y);
            path.lineTo(c.x, c.y);
            path.close();
            canvas.drawPath(path, paint);

            paint.setColor(Color.BLUE);

            Point a1 = new Point(0, 0);
            Point b1 = new Point((int)getWidth(),0);
            Point c1 = new Point((int)getWidth(), (int)getHeight());

            path1.moveTo(a1.x, a1.y);
            path1.lineTo(b1.x, b1.y);
            path1.lineTo(c1.x, c1.y);
            path1.close();
            canvas.drawPath(path1, paint);

        }
    }
}

例如,使用RelativeLayout作为背景:

RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);

ShapeDrawable background = new TwoTrianglesDrawable();
layout.setBackground(background);//Requires API 16 or higher.

0

您可以使用Android PathShape类绘制两个所需颜色的三角形


-1
这将为您提供两种颜色,垂直分割成一半。将此代码放入一个drawable资源中。

<item
    android:top="320dip">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <solid android:color="@color/red" />
    </shape>
</item>
<item android:bottom="320dip">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <solid android:color="@color/yellow" />
    </shape>
</item>


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