比如说,我想展示一个由10种语言组成的列表,这些语言都是用本地文字书写的。如果手机不支持这些字体,那么就会回退到英文文字。有没有办法检测出特定设备支持哪些字体呢? 换句话说,我只是想检查一下,比如说“旁遮普语”是否能够以“ਪੰਜਾਬੀ”的形式显示。
比如说,我想展示一个由10种语言组成的列表,这些语言都是用本地文字书写的。如果手机不支持这些字体,那么就会回退到英文文字。有没有办法检测出特定设备支持哪些字体呢? 换句话说,我只是想检查一下,比如说“旁遮普语”是否能够以“ਪੰਜਾਬੀ”的形式显示。
您还可以尝试将文本绘制成位图,并检查生成的位图是否为空白。 例如:http://www.skoumal.net/en/android-how-draw-text-bitmap 和 How to check if a Bitmap is empty (blank) on Android (当然,假设不支持的字母不会显示为黑色钻石或类似物)。
class Util {
private static final int WIDTH_PX = 200;
private static final int HEIGHT_PX = 80;
public static boolean isSupported(Context context, String text) {
int w = WIDTH_PX, h = HEIGHT_PX;
Resources resources = context.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bitmap = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Bitmap orig = bitmap.copy(conf, false);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(0, 0, 0));
paint.setTextSize((int) (14 * scale));
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int x = (bitmap.getWidth() - bounds.width()) / 2;
int y = (bitmap.getHeight() + bounds.height()) / 2;
canvas.drawText(text, x, y, paint);
boolean res = !orig.sameAs(bitmap);
orig.recycle();
bitmap.recycle();
return res;
}
}
测试代码:
String s;
s="";Log.d("~~~","=="+s+"=="+Util.isSupported(this, s));
s="中文";Log.d("~~~","=="+s+"=="+Util.isSupported(this, s));
s="ਪੰਜਾਬੀ";Log.d("~~~","=="+s+"=="+Util.isSupported(this, s));
s="Հայերեն";Log.d("~~~","=="+s+"=="+Util.isSupported(this, s));
输出:
====false
==中文==true
==ਪੰਜਾਬੀ==false
==Հայերեն==true
如果您希望在同一字符串中显示英文和本地名称,可以先检查本地名称是否应在合成两个名称的字符串之前显示,或删除拉丁字符:
public static String stripLatin(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) > 127) {
res += s.charAt(i);
}
}
return res;
}
测试代码:
s="Punjabi(ਪੰਜਾਬੀ)";Log.d("~~~","=="+s+"=="+Util.isSupported(this, Util.stripLatin(s)));
system_fonts.xml
来确认这一点。另一个支持多种语言的字体称为Droid Sans
,此处列出了它支持的语言列表。