I am trying to use a custom font on a TextView in Xamarin C#
I have the file coopbl.ttf (don't judge me, this was just to see if it worked!)
I have placed it in the following location root/Assets/Font/coopbl.ttf and marked Build Action to AndroidAssist
My XML looks as follows:
<TheKey.Classes.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="font"
android:textSize="50sp"
android:id="#+id/customFont"
custom:customFont="Font/coopbl.ttf"/>
When I call Typeface.CreateFromAsset(Context.Assets, "Font/coopbl.ttf"); I get the following exception:
Java.Lang.RuntimeException: Font asset not found Font/coopbl.ttf at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
I have followed much of the pattern used by Cheesebaron here, including the TextView.cs class: https://github.com/Cheesebaron/Cheesebaron.FontSample.
What have I missed?
Update based on comments
I tried the following with no luck, still seeing the same error:
Renamed Font directory to font then to fonts and then even tried Fonts for completeness
Removed Font/ from the method call
In Visual Studio, the Assets folder is located in the root of the project when a new Xamarin project is created, it is at the same level as Resources.
I'm using a font I found on the internet. In particular, the font that is currently causing a problem is Amaranth (Google Fonts link).
I've looked through these questions:
Native typeface cannot be made
RuntimeException: native typeface cannot be made
native typeface cannot be made, exception
custom font in android studio
All of those questions seem to be dealing with crashes that occur on the device at runtime. My problem is that I get this Exception when trying to use Android Studio's Preview tool to preview my layout.
The text I'm seeing in the "Rendering Problems" pop-up is this:
Exception raised during rendering: native typeface cannot be made
java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:147)
at android.graphics.Typeface.createFromAsset(Typeface.java:121)
at app.SegmentButton.onDraw(SegmentButton.java:79)
The code in SegmentButton is this:
#Override
public void onDraw(Canvas canvas) {
// Other code...
String fontPath = "fonts/Amaranth-Bold.otf";
// The next line is the line that causes the "crash"
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), fontPath);
textPaint.setTypeface(tf);
// Other code...
}
I have checked and ensured the following items:
My assets folder is in 'app/src/main/assets'
My fonts folder is in 'app/src/main/assets/fonts'
The file name is exactly "Amaranth-Bold.otf"
This font works exactly as desired when running my app. I have tested this on an LG Optimus Pro G as well as a Droid X. You can see the results in these images:
LG Optimus G Pro Screen Shot
Droid X Screen Shot
As you can see, the fonts show up as desired in both places. As you can probably also see, the Droid X screen shot shows some layout issues that I need to resolve. I'm trying figure out how to do this at design time using the tools built in to Android Studio. This is merely the first issue I'm tackling. I would hate to have to run the app each time in order to make small tweaks to the layout. This is especially true since these are the only two hardware devices I currently have, and I want to test on a much wider variety of screen sizes (and the emulator is sloooooooooow).
Based on my reading of other questions (and primarily based on the fact that the devices load the font fine at runtime), my current conclusions are:
The font file isn't "broken".
The font location isn't wrong.
The typed-in file name isn't wrong (extension, capitalization, etc.)
What else can I try?
I had the same problem yesterday. Android Studio gives you this tip:
Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE
Rewrite your onDraw() method like this:
#Override
public void onDraw(Canvas canvas) {
// Other code...
if(!isInEditMode())changeFont();
// Other code...
}
private void changeFont(){
String fontPath = "fonts/Amaranth-Bold.otf";
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), fontPath);
textPaint.setTypeface(tf);
}
I have an app that changes the font typeface for some elements. It works well for most of the people, but maybe a 0.5% get an exception when trying to change the font. The significant part of the stack trace is this:
Caused by: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:147)
at android.graphics.Typeface.createFromAsset(Typeface.java:121)
As I say, it works for most of the people, so I don't think it is a problem with the font file or my code. Any suggestions about how to solve this?
Edit: This is my code:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"fonts/CharisSILR.ttf");
TextView tv;
tv = ((TextView) findViewById(R.id.searchPronunciationTitle));
tv.setTypeface(phoneticFont);
This bug of Android OS could be the reason of your issue:
Typeface.createFromAsset leaks asset stream
Where are also a workaround in this bugreport:
I altered HTH's workaround so that the method does not assume the font
path or format. The full path of the font asset must be submitted as
a parameter. I also wrapped the call to createFromAsset() in a
try-catch block so that the get() method will return null if the asset
is not found.
public class Typefaces {
private static final String TAG = "Typefaces";
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(c.getAssets(),
assetPath);
cache.put(assetPath, t);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
}
I followed some of the solutions found here, with no success. I thought it was something really obscure, as programmers often do. Then somewhere I read it could be related to the font path, gotcha:
Instead of:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"blanch_caps.ttf");
I changed to:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"fonts/blanch_caps.ttf");
And my file is in assets/fonts/blanch_caps.ttf. Not it works like a charm!
This error came up when the font was in the library asset folder. When I copied it into assets of the application which was using this library, the error disappeared.
It seems assets cannot be imported:
Android Library assets folder doesn't get copied
And here are some other cases: Issue when using a custom font - "native typeface cannot be made"
I was struggling with this a lot. I tried every possibility and nothing helps. In the end, to problem was somewhere else. If you are building your project with Gradle, don't forget to add these lines in build.gradle file. This solved the problem in my case.
sourceSets {
main {
assets.srcDirs = ['assets']
}
}
You must create assets folder inside src-->main in AndroidStudio. This way worked!
In my case, it was based on the filename of the font. For some reason it was named FontName..ttf
I don't know why the double-dots were there - I looked up the original font and they were in my windows\fonts folder as FontName..ttf. Windows apparently didn't care, but Android freaked out. I renamed the file, and it's all happy now.
For my case I have found that the assets folder located in /main/java/assets but they must be in /main/assets
Do with lower case:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"fonts/charissilr.ttf");
Remember to also rename the file.
Change this one
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"fonts/CharisSILR.ttf");
to
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"CharisSILR.ttf");
I just ran into this problem when I was using the MagicTextView by qwerjk. I tried to put the MTV class in a library and use it in my main project. Here's how I got it to work:
In main project assets folder, create a subfolder called fonts
Copy the ttf file into the assets/fonts folder. My filename was camelcase (e.g. ReservoirGrunge.ttf) and so caps or no caps doesn't seem to matter.
In my main project I inflated the MTV view from xml. Make sure the MagicTextView points to the correct library path. For example, my MTV class library was com.library.library_magictextview.MagicTextView and so my main view's xml had to read:
<com.library.library_magictextview.MagicTextView
android:textSize= "50dp"
android:textColor= "#ffffffff"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:textStyle= "bold"
android:padding= "20dp"
android:gravity= "center"
r:strokeColor= "#FFff0000"
r:strokeJoinStyle= "miter"
r:strokeWidth= "5"
r:typeface= "ReservoirGrunge"
android:text= "BobDillon" />
In our situation, we had employed Hit's solution with the cache. The problem we introduced was that we were testing for OTF files AND TTF files within the same try block ;) Which is obviously going to fail on the first attempt for OTF if you're looking to get a TTF, but I thought it worth posting JUST incase it slipped passed someone's notice while they might be trying the same solution.
protected static Typeface getTypeface(Context p_context, String p_fontName){
Typeface tf = null;
try {
tf = Typeface.createFromAsset(p_context.getAssets(), "fonts/" + p_fontName + ".otf");
}catch(Exception e) {}
if( tf != null ) return tf;
try {
tf = Typeface.createFromAsset(p_context.getAssets(), "fonts/" + p_fontName + ".ttf");
}catch(Exception e) {}
return tf;
}
In my case i just deleted the assets folder (that i created manually) and just created a new one using the wizard. Apparently it wasn't read as the assets folder but read as just a normal folder and so getAssets() didn't work and gave me the error.
in android studio: what have worked for me is putting the ttf file straight to the assets folder without a sub folder of fonts , it didnt work with the sub folder ( (getAssets(),"fonts/oldengl.ttf") didnt work when i had the ttf in src/main/assets/fonts).
this works :
src/main/assets/oldengl.ttf
Typeface customfont=Typeface.createFromAsset(getAssets(),"oldengl.ttf");
I was ran in to this issue when i imported a module which was meant to support both eclipse style projects and android studio style project.
I got my issue resolved by removing the assets from the source set as-
defaultConfig {
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName '1.0'
sourceSets {
main {
java.srcDirs = ['src']
res.srcDirs = ['res']
//assets.srcDirs = ['assets']//commented this out because modlue was not having this directory
manifest.srcFile 'AndroidManifest.xml'
}
}
}
Or converting the project in to android studio style can also solve the issue I guess.
In my case,
I just use the previous code.. So I forget the font file in assets folder..
But I can`t figure out for 2 hours..
Possible cases for this error,
Font file missing
Wrong font name or wrong font extension
for ex: fonts/roboto.ttf instead of fonts/roboto.otf
I'm porting a simple tetris-like XNA app to Android, using Mono For Android and MonoGame; I have followed the suggested steps in this link and so far, everything compiles well, and no relevant warnings fire up. However, upon loading the contents, a null parameter exception breaks the program at the point below in my program:
protected override void LoadContent() {
// ...
_font = Content.Load<Microsoft.Xna.Framework.Graphics.SpriteFont>("SpriteFont1");
// ...
}
The content root directory is set in the game constructor class:
public Game2 (){
Content.RootDirectory = "Content";
Content.RootDirectory = "Assets/Content"; // TEST.
//...}
And I have tried several combinations, all to no avail.
I have also tried setting the xnb files as Content as well as Android Assets in the Build Action property; having the linked, copied always, copied only if newer... etc.
Either way, my problem is that I don't really understand WHY and HOW should I do this. I'm rather new to the platform and to XNA as well, so this may very well be a newbie question, but the truth is after several hours banging my head and fists against the monitor/keyboard I feel stuck and need your help.
I have a library that supports variable-width fonts (generated by BMFont) on MonoGame. Unfortunately it is a renderer and so has other code around it. However, the basic idea is very simple. You can take a look at the loader here and the mesh builder (given a string) here. This builder supports fonts that spread characters across multiple pages, too.
Hope this helps!
MonoGame (2.5.1) throws NotImplementedException in ContentManager.Load for SpriteFont type. Have the same not resolved problem. I'm trying not to use DrawString.
For loading textures in Win32 application I use:
Content.RootDirectory = #"../../Content";
var sampleTexture = Content.Load<Texture2D>("Sample.png");
You even must not add it to solution.
For Andoind (MonoDroid) application you must add "Content" folder to your solution and set "Andtoid Asset" in "Sample.png" properties.
Content.RootDirectory = "Content";
var sampleTexture = Content.Load<Texture2D>("Sample.png");
See also:
http://monogame.codeplex.com/discussions/360468
http://monogame.codeplex.com/discussions/267900
I'm already working on an Android application that displays RSS feed.
My problem is that this feed has some lines in Tamil(which Android still doesn't support)
I found a font online that displays the text right(without converting to Bamini) but the problem is that textStyle doesn't have any effect on it.
so you know any font that can do the job or any thing i have to do to make textStyling?
thanks in advance
What you need to do is import custom fonts on to the phone before using them.
A good way to do that is to include them in the package - in the APK file
Hence you should be having the font in your project when you build the APK file.
Let me give you an example. Assuming your tamil font's name is Harabara.ttf and you have copied it to /assets/fonts
Use this method (anywhere in your activity)
private void initializeFonts() {
font_harabara = Typeface.createFromAsset(getAssets(), "fonts/Harabara.ttf");
}
and call this API from your onCreate like this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeFonts();
setContentView(getViewResourceId());
}
Make sure you have declared this class level variable
Typeface font_harabara = null;
Finally, simply use
myTextField.setTypeface(font_harabara);
tada ! tamil font should now start displaying.
nandri vanakkam,
vaidyanathan
There are hundreds of fonts available online. Did you check some TSCII fonts?
I've written some solutions for Tamil and Android issues. Check it out too.