Created
June 19, 2019 21:46
-
-
Save afollestad/3b50ac411421e4cb078f2f168109a30b to your computer and use it in GitHub Desktop.
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
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