安卓踩坑記錄之XML位圖 - BitmapDrawable的詳細用法 (android:tileMode="repeat" 失效問題)

引言:
很久之前看到過,當時沒有去仔細研究,用了之後發現並沒有實現效果,今天才發現自己用錯了。原來它不能設置爲ImageView的src,而是應該設置爲一個任意View的background。

用法:
它是來定義View的背景的,跟你電腦桌面設置壁紙一樣,你可以設置爲橫鋪,拉伸,等各種背景樣式。這用法跟HTML背景的一些屬性有點相似。

詳細:
XML 位圖
XML 位圖是在 XML 文件中定義的資源,指向位圖文件。實際上是原始位圖文件的別名。XML 可以指定位圖的其他屬性,例如抖動和層疊。

注:您可以將 元素用作 元素的子項。例如,在創建狀態列表或圖層列表時,可以將 android:drawable 屬性從 元素中排除,並在其中嵌套用於定義可繪製項的 。
文件位置:
res/drawable/filename.xml
文件名用作資源 ID。
編譯資源的數據類型:
指向 BitmapDrawable 的資源指針。
資源引用:
在 Java 中:R.drawable.filename
在 XML 中:@[package:]drawable/filename

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@[package:]drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
                      "fill_vertical" | "center_horizontal" | "fill_horizontal" |
                      "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:mipMap=["true" | "false"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

元素:
bitmap
定義位圖來源及其屬性。
xmlns:android
字符串。定義 XML 命名空間,其必須是 “http://schemas.android.com/apk/res/android”。這僅當 是根元素時才需要,當 嵌套在 內時不需要。
android:src
可繪製對象資源。必備。引用可繪製對象資源。
android:antialias
布爾值。啓用或停用抗鋸齒。
android:dither
布爾值。當位圖的像素配置與屏幕不同時(例如:ARGB 8888 位圖和 RGB 565 屏幕),啓用或停用位圖抖動。
android:filter
布爾值。啓用或停用位圖過濾。當位圖收縮或拉伸以使其外觀平滑時使用過濾。
android:gravity
關鍵字。定義位圖的重力。重力指示當位圖小於容器時,可繪製對象在其容器中放置的位置。
必須是以下一個或多個(用 ‘|’ 分隔)常量值:
在這裏插入圖片描述
android:mipMap
布爾值。啓用或停用 mipmap 提示。如需瞭解詳情,請參閱 setHasMipMap()。默認值爲 false。
android:tileMode
關鍵字。定義平鋪模式。當平鋪模式啓用時,位圖會重複。重力在平鋪模式啓用時將被忽略。
必須是以下常量值之一:
在這裏插入圖片描述
示例:
android:tileMode=[“disabled” | “clamp” | “repeat” | “mirror”] ,共四個屬性,分別代表拉伸,原圖大小,橫鋪,鏡像,這裏展示橫鋪效果。

res/drawable/test_bit_one.xml:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_launcher_round"
    android:dither="true"
    android:tileMode="repeat"/>

佈局代碼:

    <ImageView
        android:background="@drawable/test_bit_one"
        android:id="@+id/iv_main_icon"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

效果:
在這裏插入圖片描述
引用資源鏈接:
所有相關屬性均來自安卓官方文檔:可繪製對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章