Background with two colors

5

I would like to create a background with two colors at a 45 degree angle, but without transition. I did it this way:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:type="linear"
    android:startColor="#000"
    android:endColor="#FFF"
    android:angle="45"/>

</shape>

The problem is that you get a transition, like this:

I'dlikesomethingwithoutthis"transition":

    
asked by anonymous 15.05.2016 / 07:12

1 answer

2

In XML I do not know if it's possible. In Java, a possible way is to create a Shape and build a ShapeDrawable with it.

TwoTrianglesDrawable.java

public class DoisTriangulosDrawable extends ShapeDrawable {

    public DoisTriangulosDrawable(){
        super();
        setShape(new DoisTriangulosShape());
    }

    private class DoisTriangulosShape 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.BLACK);

            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.RED);

            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);

        }
    }
}

To use, for example, background of a RelativeLayout :

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

ShapeDrawable background = new DoisTriangulosDrawable();
layout.setBackground(background);//Requer API16 ou superior
    
15.05.2016 / 22:28