Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 入門教程(16):圖片顯示與畫布繪圖實戰

編輯:關於 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 會輕鬆很多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved