[关闭]
@TryLoveCatch 2022-05-05T08:39:52.000000Z 字数 2355 阅读 863

Android知识体系之各种drawable

Android知识体系


前言

一般Drawable都会有两种方式来表示,一种就是代码里面直接new,另一种就是使用xml,接下来我都会从这两个方向来介绍。

关于ConstantState

ConstantState可以参看上一篇Bitmap优化之一张图片实现点击效果里面的介绍:

Drawable比作一个绘制容器,那么ConstantState就是容器中真正的内容。ConstantStateDrawable的静态内部类。具体的实现都在Drawable子类里面

我们在研究各个Drawable的时候,可以注意一下,基本上每一个Drawable都会有一个内部类ConstantState

ColorDrawable

代码

  1. ColorDrawable drawable = new ColorDrawable(0xffff2200);
  2. txtShow.setBackground(drawable);

xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <color
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:color="#FF0000"/>

对于ColorDrawable,其实,我们一般都不会这么使用,我们一般都是在colors.xml里面定义一个color,然后再代码或者xml里面使用。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <color name="color_r">#fff5f5f5</color>
  4. </resources>
  1. txtShow.setBackgroundColor(R.color.color_r);

我们可以看下setBackgroundColor()的源码:

  1. public void setBackgroundColor(int color) {
  2. if (mBackground instanceof ColorDrawable) {
  3. ((ColorDrawable) mBackground.mutate()).setColor(color);
  4. computeOpaqueFlags();
  5. mBackgroundResource = 0;
  6. } else {
  7. setBackground(new ColorDrawable(color));
  8. }
  9. }

很显然,它也是构造了一个ColorDrawable,然后调用的setBackground()

NinePatchDrawable

这个应该也是咱们经常用到的,它就是.9图片了。这个就比较简单,大多数,我们都是直接使用切图来实现的,这个了解就行,NinePatchDrawable是给系统用的,我们基本上用不到。

BitmapDrawable

最常用的Drawable

代码

  1. BitmapDrawable bitDrawable = new BitmapDrawable(bitmap);
  2. bitDrawable.setDither(true);
  3. bitDrawable.setTileModeXY(TileMode.MIRROR,TileMode.MIRROR);

xml

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

src:图片资源~
antialias:是否支持抗锯齿
filter:是否支持位图过滤,支持的话可以是图片显示时比较光滑,为了使图片被放大或者缩小时有一个较好的显示效果
dither:是否对位图进行抖动处理,作用是手机像素配置和图片像素配置不一致时,系统会自动调整显示效果。例如:一个位图的像素设置是 ARGB 8888,但屏幕的设置是RGB 565。
gravity:若位图比容器小,可以设置位图在容器中的相对位置
tileMode:指定图片平铺填充容器的模式,设置这个的话,gravity属性会被忽略,有以下可选值:
disabled(不平铺位图。这是默认值),clamp(原图大小),
repeat(平铺),mirror(镜像平铺)

当我们在这里使用了除disable之外的另外三种取值时,gravity属性值失效。

关于titleMode的几个值,我们直接上图说效果:
原图:

repeat:

clamp:

mirror:为了说明效果,换了一张图

Xml方式,可以对原始的位图进行一系列的处理,比如说抗锯齿,拉伸,对齐等等。

参考

Google官方文档
Android中的13种Drawable小结
Android Drawable Resource学习(二)、BitmapDrawable和Bitmap
玩转Android之Drawable的使用

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注