Android 应用中带圆角的方形图标

square icon with rounded corners in an Android app

以下 kotlin 代码用于在 Android 应用程序中显示方形图标。 但我也想给它设置圆角;这就是问题所在。 任何提示都将受到欢迎,因为如何使圆角工作。

    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 ...

将 cornerRadius 替换为您想要的角半径。

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.

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.