AmosKorir / AvatarImageGenerator

Android library to generate image avatar from the first letter of a username. Letter avatar like Gmail Android best practice
https://medium.com/@koriramos/android-first-letter-avatar-image-generator-91c1f314eeb4
Apache License 2.0
73 stars 20 forks source link

gradient color in background #16

Open kalpeshat20 opened 3 years ago

kalpeshat20 commented 3 years ago

is there any way to add a gradient color in background?

AmosKorir commented 3 years ago

At the moment that is not supported,

payal-iroid commented 11 months ago

I have modified the avatarImageGenerate() function to display gradient background and it is working fine. Hope this helps @kalpeshat20

   private fun avatarImageGenerate(context: Context, size: Int, shape: Int, name: String, colorStr: String): BitmapDrawable {
            uiContext = context
            texSize = calTextSize(size)
            val label = firstCharacter(name)
            val textPaint = textPainter()
            val painter = painter()
            painter.isAntiAlias = true
            val areaRect = Rect(0, 0, size, size)

            if (shape == 0) {
                val firstLetter = firstCharacter(name)
//                val r = firstLetter[0]
                //Random rnd = new Random();
                //int color = generateRandomColor();// Color.argb(255, rnd.nextInt(100), rnd.nextInt(150), rnd.nextInt(256));
                val color = if (!colorStr.isNullOrEmpty()) Color.parseColor(colorStr) else RandomColors().getColor()

                painter.color = color
                painter.shader = LinearGradient(size.toFloat() / 3, size.toFloat() / 4, 0F, size.toFloat(), color, Color.WHITE, Shader.TileMode.CLAMP)
            } else {
                painter.color = Color.TRANSPARENT
            }

            val bitmap = Bitmap.createBitmap(size, size, ARGB_8888)
            val canvas = Canvas(bitmap)
            canvas.drawRect(areaRect, painter)

            //reset painter
            if (shape == 0) {
                painter.color = Color.TRANSPARENT
            } else {
                val firstLetter = firstCharacter(name)
                val color = if (!colorStr.isNullOrEmpty()) Color.parseColor(colorStr) else RandomColors().getColor()
                painter.color = color;
                painter.shader = LinearGradient(size.toFloat() / 3, size.toFloat() / 4, 0F, size.toFloat(), color, Color.WHITE, Shader.TileMode.CLAMP);
            }

            val stringWidth = textPaint.measureText(label);
            val xPosition = (canvas.clipBounds.width() / 2f) - (stringWidth / 2f);
            val yPosition = (canvas.clipBounds.height() / 2f) - ((textPaint.ascent() + textPaint.descent()) / 2f);
            canvas.drawCircle(size.toFloat() / 2, size.toFloat() / 2, size.toFloat() / 2, painter);
            canvas.drawText(label, xPosition, yPosition, textPaint);
            return BitmapDrawable(uiContext.resources, bitmap)

        }