Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created June 19, 2019 21:46
Show Gist options
  • Save afollestad/3b50ac411421e4cb078f2f168109a30b to your computer and use it in GitHub Desktop.
Save afollestad/3b50ac411421e4cb078f2f168109a30b to your computer and use it in GitHub Desktop.
import android.graphics.Typeface
import androidx.annotation.CheckResult
import java.lang.Exception
/** @author Aidan Follestad (@afollestad) */
object TypefaceHelper {
private val cache = hashMapOf<String, Typeface>()
/**
* Gets a typeface by its family name. Automatically statically caches it to avoid
* repeated allocations.
*/
@CheckResult fun create(familyName: String): Typeface {
return cache[familyName] ?: allocateAndCache(familyName)
}
private fun allocateAndCache(familyName: String): Typeface {
return try {
Typeface.create(familyName, Typeface.NORMAL)
.also { cache[familyName] = it }
} catch (e: Exception) {
Typeface.DEFAULT
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment