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

用 XML shape 畫出圓形底色,搭配透明前景圖

編輯:關於 Android 開發

有時候設計稿要的是「圓形色塊 + 中間一張圖」,與其請設計多切一張圖,不如用 XML 的 shape 標籤直接畫出來,既清晰又方便改色。

一、ImageView 的設定

把圓形當背景、透明圖當前景,並用 centerInside 讓圖片完整置中呈現:

<ImageView
    android:id="@+id/zhongjie"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/mark_caller_house_agent"
    android:scaleType="centerInside"
    android:src="@drawable/背景圖" />

二、圓形背景定義

新增 res/drawable/mark_caller_house_agent.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="false">

    <solid android:color="#66CC00" />
    <size
        android:width="50dp"
        android:height="50dp" />

</shape>

三、效果

幾個可調參數

除了 solid 填色,shape 還支援這些實用標籤:

  • <stroke>:加上外框線,可指定 width、color、dashWidth、dashGap
  • <corners android:radius="8dp" />:把 oval 換成 rectangle 後可做出圓角方塊
  • <gradient>:需要漸層時取代 solid

另外提醒,scaleType 請依實際需求挑選:centerInside 適合「圖比框小、要完整顯示」,若圖片本身就是設計好的完整圖示,center 也是常見選擇。

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