Search code examples
javaandroidkotlinlayout

draw layout with skewed corners in android


I need to draw skewed corners in my layout , basically my layout height is 60dp , i have tried to do them using an xml file of layer-list , but it is not giving the desired specially when devices gets larger in screen , i would like to get some help or if possible to draw these skewed corners programmatically so they fix into all screens and when also screen is rotated , Thank you

  • This is my xml file
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/bgColor" />
    
    <item android:top="-20dp"
        android:bottom="-50dp"
        android:left="-20dp"
        android:right="400dp">
        <rotate
            android:fromDegrees="368"
            android:pivotX="50%"
            android:pivotY="00%">
            <shape
                android:shape="rectangle">
                <solid android:color="#DFDBDB"/>
            </shape>
        </rotate>
    </item>
    <item android:top="-20dp"
        android:bottom="-50dp"
        android:left="395dp"
        android:right="-120dp">
        <rotate
            android:fromDegrees="-371"
            android:pivotX="50%"
            android:pivotY="00%">
            <shape
                android:shape="rectangle">
                <solid
                    android:color="?android:colorBackground"/>
            </shape>
        </rotate>
    </item>
</layer-list>

  • Desired Result

enter image description here


Solution

  • calculating the coordinates of points to join Path() is the most important thing in your work. my calculation is based on the width of the View. Hope it can help you.

    class SkewedCornerView(context: Context, attrs: AttributeSet?) : View(context, ttrs) {
    
        private val path = Path()
        val paint = Paint().apply {
            flags = Paint.ANTI_ALIAS_FLAG
            color = Color.WHITE
            style = Paint.Style.STROKE
        }
    
        override fun onDraw(canvas: Canvas?) {
    //        super.onDraw(canvas)
            val padding = height/50f
            paint.strokeWidth = padding
            canvas?.drawColor(Color.BLACK)
            canvas?.apply {
                path.reset()
                val cornerSize = width / 15f
                val width = width.toFloat()
                val height = height.toFloat()
    //            path.moveTo(padding, height-padding)
                path.moveTo(padding, height/2)
                path.lineTo(cornerSize, padding)
                path.lineTo(width - cornerSize-padding, padding)
                path.lineTo(width-padding, height/2)
    //            path.lineTo(width-padding, height-padding)
    //            path.lineTo(padding, height-padding)
    //            path.close()
                drawPath(path, paint)
            }
        }
    }