自定义字体必须放到asset目录下,由于在android在layout的xml不支持直接使用自定义字体,所以我们需要调用context.getAssets()方法获取自定义字体的资源,由于android Widget是依赖于其他进程存在,故widget中无法使用字体设置的.setTypeface方法,因此在Widget中使用自定义字体,可以将字体转换为图片输出以后,用views.setImageViewBitmap方法可实现自定义功能,参考代码:
static Bitmap buildUpdate(String time, Context context){
Bitmap myBitmap = Bitmap.createBitmap(240, 80, Bitmap.Config.ARGB_4444);
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Typeface clock = Typeface.createFromAsset(context.getAssets(),"fonts/Clockopia.ttf");
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(clock);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(80);
paint.setTextAlign(Align.CENTER);
myCanvas.drawText(time, 100, 60, paint);
return myBitmap;
}
//widget中调用
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_main);
views.setImageViewBitmap(R.id.imageView1, buildUpdate(time,context));