Created
November 28, 2023 07:09
-
-
Save ridcully99/22be5fcb3b1babf39945d00b1d2602af to your computer and use it in GitHub Desktop.
An Identicon Drawable for Android, written in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// written by Robert Brandner | |
// Based on https://github.com/stewartlord/identicon.js | |
// | |
import android.graphics.Canvas | |
import android.graphics.ColorFilter | |
import android.graphics.Paint | |
import android.graphics.PixelFormat.TRANSPARENT | |
import android.graphics.Rect | |
import android.graphics.drawable.Drawable | |
import androidx.core.graphics.ColorUtils | |
import androidx.core.graphics.withScale | |
import androidx.core.graphics.withTranslation | |
import java.security.MessageDigest | |
class IdenticonDrawable(string : String) : Drawable() { | |
private val hash = md5Hash(string) | |
private val pixels = hash.take(15).toCharArray().map { it.digitToInt(16) % 2 } | |
private val rect = Rect(0, 0, 1, 1) | |
private val paint = Paint().apply { | |
val hue = (hash.takeLast(7).toInt(16).toFloat() / 0xfffffff) * 360f | |
val saturation = 0.7f | |
val lightness = 0.5f | |
this.color = ColorUtils.HSLToColor(floatArrayOf(hue, saturation, lightness)) | |
} | |
override fun draw(canvas: Canvas) { | |
// Get the drawable's bounds | |
val width: Int = bounds.width() | |
val height: Int = bounds.height() | |
fun Canvas.drawPixel(x: Int, y: Int, pixel: Int) { | |
if (pixel == 0) return | |
withTranslation(x.toFloat(), y.toFloat()) { | |
drawRect(rect, paint) | |
} | |
} | |
canvas.withScale(width / 5f, height / 5f) { | |
for (i in 0..4) { | |
drawPixel(2, i, pixels[i]) | |
drawPixel(1, i, pixels[i+5]) | |
drawPixel(3, i, pixels[i+5]) | |
drawPixel(0, i, pixels[i+10]) | |
drawPixel(4, i, pixels[i+10]) | |
} | |
} | |
} | |
override fun setAlpha(alpha: Int) { | |
// | |
} | |
override fun setColorFilter(colorFilter: ColorFilter?) { | |
// | |
} | |
@Deprecated("Deprecated in Java") | |
override fun getOpacity(): Int = TRANSPARENT | |
@OptIn(ExperimentalStdlibApi::class) | |
private fun md5Hash(string: String): String = | |
MessageDigest.getInstance("MD5") | |
.digest(string.toByteArray()).toHexString(HexFormat.Default) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment