Background with two colors

Asked

Viewed 152 times

5

I would like to create a background with two colors at an angle of 45 degrees, but no 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 you get a transition, like this: inserir a descrição da imagem aqui

I’d like something without this "transition": inserir a descrição da imagem aqui

  • you want that "line" with 45º exactly or you want that line to go from one diagonal to the other?

1 answer

2

In XML I don’t know if it’s possible.
In Java, one possible way is to create a Shape and build a Shapedrawable with her.

Doistriangulosdrawable.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, as background of a Relativelayout:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.