編輯:關於 Android 程式設計
做圖相關的功能,繞不開圖片格式這個話題。jpg、png、webp 各自的適用場景值得花時間了解一下,這既是知識積累,面試時也常被問到。
先看兩個運行效果:


三個按鈕分別負責「顯示資源圖片」「顯示並在圖片上作畫」「在控件上作畫」,下面跟一個 ImageView 承載結果。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:id="@+id/Button01"
android:layout_width="fill_parent" android:layout_height="55dp"
android:text="顯示資源圖片" />
<Button android:id="@+id/Button02"
android:layout_width="fill_parent" android:layout_height="55dp"
android:text="顯示並繪畫資源圖片" />
<Button android:id="@+id/Button03"
android:layout_width="fill_parent" android:layout_height="55dp"
android:text="在控件上繪圖" />
<ImageView android:id="@+id/ImageView01"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
三個按鈕共用一個監聽器,靠引用比較來分流處理。註釋我保留得比較細,直接看代碼更直觀。
Bitmap bmp = BitmapFactory.decodeResource(r, R.drawable.fable5); iv.setImageBitmap(bmp);
這裡的效果和 iv.setBackgroundResource(R.drawable.fable5) 等價,只是路徑不同:一個解成 Bitmap 交給 ImageView,一個直接把 Drawable 掛上去。
BitmapFactory.decodeResource() 解出來的 Bitmap 是只讀的,不能直接在上面畫。所以我們新建一張位圖,把原圖「搬」到新畫布上,再往上加內容:
Bitmap newb = Bitmap.createBitmap(300, 300, Config.ARGB_8888);
Canvas canvasTemp = new Canvas(newb); // 以 newb 為畫布
canvasTemp.drawColor(Color.TRANSPARENT); // 背景設為透明
Paint p = new Paint();
Typeface font = Typeface.create("宋體", Typeface.BOLD);
p.setColor(Color.RED);
p.setTypeface(font);
p.setTextSize(24);
canvasTemp.drawText("肥寶傳說之路", 50, 50, p);
canvasTemp.drawBitmap(bmp, 50, 50, p);
iv.setImageBitmap(newb);
顺带一提,如果遊戲裡要用非系統字體,把字體文件放到 assets/fonts/ 目錄下,用 Typeface.createFromAsset() 加載即可。
思路相同,只是畫布尺寸改成按鈕自身的寬高,畫完再作為背景設回去:
Bitmap newb = Bitmap.createBitmap(btn3.getWidth(), btn3.getHeight(), Config.ARGB_8888);
Canvas canvasTemp = new Canvas(newb);
canvasTemp.drawColor(Color.WHITE);
Paint p = new Paint();
p.setColor(Color.BLUE);
p.setTypeface(Typeface.create("宋體", Typeface.BOLD));
p.setTextSize(24);
canvasTemp.drawText("Android 新手入門 2016", 14, 24, p);
Drawable drawable = new BitmapDrawable(getApplicationContext().getResources(), newb);
btn3.setBackgroundDrawable(drawable);
這裡有個容易踩的坑:文字坐標千萬別寫得超出按鈕範圍,否則畫上去也看不見。
運行結果:


整體來看,Android 的繪圖體系就是「畫布 + 畫筆」的組合:Bitmap 提供像素載體,Canvas 負責落筆,Paint 決定顏色、線寬、字形等一切呈現細節。理解這三者的分工,後面寫自定義 View 會輕鬆很多。
React Native 的 ViewPagerAndroid 用法詳解
ViewPager 是 Android 裡常見的頁面切換控件,UIExplorerApp 中也提供了 ViewPagerAndroid 的示例。通過動手實現這個控件,可以
Android 數據讀取與寫入(二):讓設定記住用戶的選擇
完成效果:選擇選項後退出,介面能記住用戶選擇的選項。 1. 利用 SharedPreferences 記住選擇的選項 主佈局:
Android Studio 配置與使用 SVN 版本控制完整指南
一、配置 SVN 客戶端 Android Studio 關聯 SVN 並不複雜。進入 Settings,找到 Version Control → Subversion,在
Unity3D UNET 模仿局域網遊戲(二):血量、血條與同步
加入血量 角色能射擊後,需要加入生命值。可以為 Player 建立 Health 腳本,定義最大血量與目前血量,並提供 TakeDamage 方法。當血量小於等於 0 時