安卓踩坑记录之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" />

效果:
在这里插入图片描述
引用资源链接:
所有相关属性均来自安卓官方文档:可绘制对象

发布了61 篇原创文章 · 获赞 89 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/tran_sient/article/details/104600279
今日推荐