【发布时间】:2016-04-10 12:57:27
【问题描述】:
我想通过在 android 中使用 xml 来制作这样的东西。我使用 45 度角的渐变实现了类似的效果,但我不想要渐变而是像这样的纯色。非常感谢任何建议。提前致谢。
这就是我想用 xml 做的。
我需要很多这样的,所以我无法在可绘制文件夹中加载位图。]1
【问题讨论】:
标签: android xml drawable android-drawable xml-drawable
我想通过在 android 中使用 xml 来制作这样的东西。我使用 45 度角的渐变实现了类似的效果,但我不想要渐变而是像这样的纯色。非常感谢任何建议。提前致谢。
这就是我想用 xml 做的。
我需要很多这样的,所以我无法在可绘制文件夹中加载位图。]1
【问题讨论】:
标签: android xml drawable android-drawable xml-drawable
您可以使用 Android PathShape 类绘制两个所需颜色的三角形
【讨论】:
下面的答案是从How to make gradient background in 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 文件,将上述代码复制并粘贴到此文件中。
谢谢。
【讨论】:
我不知道在 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.
【讨论】:
这将给你两种颜色一半和一半垂直。将此代码放入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>
【讨论】: