![](/img/trans.png)
[英]What are the requirements for a font (OTF or TTF) so it works well on Android?
[英]Android font ttf or otf typeface rendering random symblols/letters
我有一個自定義View
,我正在繪制一些文本。 我正在使用資產文件夾中提供的各種免費otf / ttf字體文件
public class ProjectView extends View {
private final Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private void init(Context context) {
textPaint.setStyle(Paint.Style.FILL);
textPaint.setAntiAlias(true);
typeface = Typeface.createFromAsset(context.getAssets(), "fonts" + File.separator + fontFileName);
textPaint.setTypeface(typeface);
}
}
一切似乎工作得很好,除了一件事:我正在繪制的單詞隨機亂搞,意味着字母隨機替換為其他字母或符號。
這是一個例子:
正確的單詞位於左側圖像中,但有時會像右圖中一樣繪制。 再次調用invalidate()
再次正確呈現所有內容可以解決問題。
這個效果在ListView
更明顯,因為頻繁的重繪,因為我在每個項目點擊時調用notifyDatasetChanged()
。 在適配器中我使用它像這樣:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.list_item_fonts, null);
holder = new ViewHolder();
holder.txtFont = (TextView) view.findViewById(R.id.txtFont);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
//tried this two but no success
holder.txtFont.setPaintFlags(holder.txtFont.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG | Paint.DEV_KERN_TEXT_FLAG);
holder.txtFont.getPaint().setSubpixelText(true);
holder.txtFont.setTextSize(TypedValue.COMPLEX_UNIT_SP, fonts.get(position).getSize());
holder.txtFont.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts" + File.separator + font.getFileName()));
}
說實話,我不知道是什么導致這種情況或如何阻止它。 任何幫助表示贊賞!
每次調用getView時都會創建字體。 這是低效的,並且可能在加載和解析字體文件時引起競爭。
而是在活動中具有所有加載的字體的映射,並且僅加載每個字體。
如果許多活動和視圖使用相同的字體,我甚至會嘗試管理Application類上的字體。
可能這可能對某人有所幫助。 我遇到了同樣的問題。 我用lru
緩存解決了它。
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
import android.util.LruCache;
public class TypefaceSpan extends MetricAffectingSpan {
private static LruCache<String, Typeface> sTypefaceCache = new LruCache<>(12);
private Typeface mTypeface;
public TypefaceSpan(Context context, String typefaceName) {
mTypeface = sTypefaceCache.get(typefaceName);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),
String.format("fonts/%s", typefaceName));
sTypefaceCache.put(typefaceName, mTypeface);
}
}
@Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
@Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(mTypeface);
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
}
例:
private TypefaceSpan typefaceSpan;
構造函數:
typefaceSpan = new TypefaceSpan(context, "name_of_font.otf");
getView:
typefaceSpan.updateDrawState(holder.title.getPaint());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.