androidsvg
androidsvg copied to clipboard
Why are you can't support font-face???
We don't currently support @font-face, but I could add it to the TODO list if you want.
However you can use custom fonts now by using SimpleAssetResolver.
-
Add the following to your code:
SVG.registerExternalFileResolver( new SimpleAssetResolver(context.getAssets()) ); -
Add the custom font you want to use to your
assetsfolder. Eg.Verdana.ttf. -
To use it in your SVG, you can then do something like:
<text font-family="Verdana" ...
The font family name must be the same as the file name. Both .ttf and .otf fonts are supported.
To use within resources implement this
/**
* A sample implementation of [SVGExternalFileResolver] that retrieves files from
* an application's "res/font" folder.
*/
class SimpleResResolver(private val context: Context) : SVGExternalFileResolver() {
override fun resolveFont(fontFamily: String?, fontWeight: Int, fontStyle: String?): Typeface? {
return with(context) {
try {
fontFamily ?: return null
val id = resources.getIdentifier(fontFamily.normalize(), "font", packageName)
ResourcesCompat.getFont(applicationContext, id)
} catch (e: Throwable) {
null
}
}
}
override fun resolveImage(filename: String?): Bitmap? {
return with(context) {
try {
filename ?: return null
val id = resources.getIdentifier(filename.normalize(), "drawable", packageName)
BitmapFactory.decodeResource(resources, id)
} catch (e: Throwable) {
null
}
}
}
override fun resolveCSSStyleSheet(url: String?): String? {
return with(context) {
try {
url ?: return null
val name = URLUtil.guessFileName(url, null, null)
val id = resources.getIdentifier(name.normalize(), "raw", packageName)
resources.openRawResource(id)
.bufferedReader()
.use(BufferedReader::readText)
} catch (e: Throwable) {
null
}
}
}
override fun isFormatSupported(mimeType: String?): Boolean {
return supportedFormats.contains(mimeType)
}
companion object {
private val nonAsciiRegex = "[^\\x00-\\x7F]".toRegex()
private val supportedFormats = HashSet<String>(8)
init {
supportedFormats.add("image/svg+xml")
supportedFormats.add("image/jpeg")
supportedFormats.add("image/png")
supportedFormats.add("image/pjpeg")
supportedFormats.add("image/gif")
supportedFormats.add("image/bmp")
supportedFormats.add("image/x-windows-bmp")
supportedFormats.add("image/webp")
}
private fun String.normalize(): String {
return replace(nonAsciiRegex, "")
.toLowerCase(Locale.getDefault())
.replace('-', '_')
}
}
}