Android—TTF字型

來源:互聯網
上載者:User

Android中不支援layout的xml 直接使用TTF等自訂字型  

自訂字型必須放到asset目錄下,需要調用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 tf= Typeface.createFromAsset(context.getAssets(),"fonts/Clockopia.ttf"); 

        paint.setAntiAlias(true); 
        paint.setAlpha(110);//取值範圍為0~255,值越小越透明 
        paint.setSubpixelText(true); 
        paint.setTypeface(tf); 
        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中調用     製作顯示時間的案頭widget時調用
RemoteViews mViews = new RemoteViews(context.getPackageName(), R.layout.main); 
mViews.setImageViewBitmap(R.id.imageView1, buildUpdate(time,context)); 

PS:因為使用了畫筆和映像來實現字型,所以布局時要用<ImageView>。 

 

PPS: 
widget 僅支援簡單組件,比如ImageView,textvew,不支援進階複雜的組件,比如listview,Edittext。但是widget可以點擊觸發含有任何組件的activity。具體步驟是: 

[html]   代碼需要放置在onUpdate( )方法中執行

  RemoteViews(context.getPackageName(),R.layout.main); 
 Intent intent = new Intent(context,被調用activity.class); 
 PendingIntent pend = PendingInent.getActivity(context,0,intent,0); 
 mRemoteViews.setOnClickPendingIntent(R.id.widget,pend);。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.