Home > Enterprise >  square icon with rounded corners in an Android app
square icon with rounded corners in an Android app

Time:05-27

The following kotlin code is used to display a square icon in an Android app. But I would also like to set rounded corners to it; and this is where things go wrong. Any tip would be welcome as what to do to get the rounded corners working.

    val apIcnID = resources.getIdentifier("appIcon","id",packageName)
    val apIcnCompo = findViewById<ImageView>(apIcnID)

    val borderSz = 9F; val cornerRad = 16F
    val shape = ShapeDrawable(
        RoundRectShape(
            floatArrayOf(cornerRad, cornerRad, cornerRad, cornerRad,
                cornerRad, cornerRad, cornerRad, cornerRad),
            RectF(borderSz, borderSz, borderSz, borderSz),
            floatArrayOf(cornerRad, cornerRad, cornerRad, cornerRad,
                cornerRad, cornerRad, cornerRad, cornerRad)
        )
    )

    //apIcnCompo.clipToOutline = true // Uncommenting this line hides the whole image.
    apIcnCompo.background = shape
    apIcnCompo.setImageResource(R.drawable.ic_launcher_myapp)
    // I see the square-icon image, but with no single rounded corner ...

CodePudding user response:

Replace cornerRadius with your desired corner radius.

val apIcnID = resources.getIdentifier("appIcon","id",packageName)
val apIcnCompo = findViewById<ImageView>(apIcnID)
    
val borderSz = 9F; val cornerRad = 16F
// similarCornerRadius
val roundCorners = FloatArray(8) { cornerRadius }        


val shape  = ShapeDrawable().apply {
        shape = RoundRectShape(roundCorners, null, null)
        paint.color = Color.RED
    }
apIcnCompo.background = shape
apIcnCompo.setImageResource(R.drawable.ic_launcher_myapp)
apIcnCompo.clipToOutline = true // Added by @Michel.

OR

val apIcnID = resources.getIdentifier("appIcon","id",packageName)
val apIcnCompo = findViewById<ImageView>(apIcnID)
    
val borderSz = 9F; val cornerRad = 16F
// similarCornerRadius
val roundCorners = FloatArray(8) { cornerRadius }        

apIcnCompo.setImageResource(R.drawable.ic_launcher_myapp)

val gd = GradientDrawable();
//gd.Color(Color.RED); // Edited by @Michel.
//gd.CornerRadius(10); // Edited by @Michel.
//gd.Stroke(2, Color.WHITE); // Edited by @Michel. (3 next lines)
gd.setColor(Color.RED)
gd.cornerRadius = 10F
gd.setStroke(2,Color.WHITE)

apIcnCompo.setBackground(gd);
apIcnCompo.clipToOutline = true // Added by @Michel.
  • Related