Search code examples
androidandroid-layoutdrawable

how to make sharp gradient drawable


i want to make a sharp black and white gradient like this enter image description here

all i did is this

enter image description here

this is my drawable file

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:startColor="#000"
    android:endColor="#fff"
    android:centerColor="#fff"
    />
</shape>

any idea how to make it!


Solution

  • As others already noticed, the effect you want to achive isn't a gradient. If I understand you are trying to achieve flexible image, divided 1:1.

    Getting this is not possible neither via .xml file nor via 9patch (then you lose sharp transition between black and white).

    First solution is to use LinearLayout and layout_weights. You can add a 'layer' to your layout - if it would be background - under other components. This 'layer' looks like that:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/black"/>
    
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/white"/>
    
    </LinearLayout>
    

    If you use it once or twice in your layout this additional/nested layout would not be a problem, but avoid such solutions inside collection items.


    You can also try with ordinary two-color png file and ImageView. (Tip: Suitable dimensions of this file can give you sharp transition.)


    Third way to do it, the lightest one, but a little time consuming is to override View.onDraw() method and paint both halves before other content would be drawn.