Drawable Resources

Drawable Resources

@(Android)


API Guides

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon. There are several different types of drawables:

FILE LOCATION:

res/drawable/filename
The filename is used as the resource ID.

RESOURCE REFERENCE:

In Java: R.drawable.filename
In XML: @[package:]drawable/filename

Bitmap

BitmapDrawable

A bitmap image. Android supports bitmap files in three formats: .png (preferred), .jpg (acceptable), .gif (discouraged).

You can reference a bitmap file directly, using the filename as the resource ID, or create an alias resource ID in XML.

Android支持三种格式的Bitmap文件:.png .jpg .gif。在开发中,可以直接使用原始的 Bitmap,也可以通过 XML Bitmap。

Note: Bitmap files may be automatically optimized with lossless image compression by the aapt tool during the build process. If you plan on reading an image as a bit stream in order to convert it to a bitmap, put your images in the res/raw/ folder instead, where they will not be optimized.

Bitmap File

A bitmap file is a .png, .jpg, or .gif file. Android creates a Drawable resource for any of these files when you save them in the res/drawable/ directory.

当将Bitmap文件保存在 res/drawable/ 目录时,Android会创建相应的Drawable资源。

XML文件中将图片转换为View

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/myimage" />

Java代码中从资源文件获取图片

Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.myimage);

XML Bitmap

Studio中使用会报错。Eclipse中能使用,但是效果出不来。

XML Bitmap可以对原始的Bitmap进行一系列的处理,比如说抗锯齿,拉伸,对齐等等。

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@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"] />

android:antialias: 抗锯齿

Boolean. Enables or disables antialiasing.

是否开启图片抗锯齿功能。开启后会让图片变得平滑。(建议开启)

android:dither:抖动

Boolean. Enables or disables dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen (for instance: a ARGB 8888 bitmap with an RGB 565 screen).

如果图片与屏幕的像素配置不一致时,是否开启抖动效果.
+ true:开启抖动效果。(默认为true)
+ false:不开启抖动效果

开启抖动效果,可以让图片能保持较好的显示效果。(建议开启)

android:filter:过滤

Boolean. Enables or disables bitmap filtering. Filtering is used when the bitmap is shrunk or stretched to smooth its apperance.

是否开启过滤效果。当图片尺寸被拉伸或者压缩时,开启过滤效果可以保持较好的显示效果。(建议开启)

android:gravity

Keyword. Defines the gravity for the bitmap. The gravity indicates where to position the drawable in its container if the bitmap is smaller than the container.

当控件小于容器的尺寸时,通过此选项可以设置控件在容器中放置的位置。

android:mipMap

Boolean. Enables or disables the mipmap hint. See setHasMipMap() for more information. Default value is false.

这是一种图像相关的处理技术,也叫纹理映射,比较抽象,默认值为 false。开发中不常用。

android:tileMode:平铺模式

Keyword. Defines the tile mode. When the tile mode is enabled, the bitmap is repeated. Gravity is ignored when the tile mode is enabled.

当开启平铺模式时,bitmap是重复的,并且android:gravity属性将被忽略。

ValueDescription
disabled关闭平铺模式(默认)
clamp扩展边缘颜色填充容器
repeat简单的水平和竖直方向上的平铺效果
mirror在水平和竖直方向上的镜面投影效果

Nine-Patch File

NinePatchDrawable

A NinePatch is a PNG image in which you can define stretchable regions that Android scales when content within the View exceeds the normal image bounds.

Same as with a normal bitmap, you can reference a Nine-Patch file directly or from a resource defined by XML.

NinePatchDrawable 表示的是 .9 格式的PNG图片,.9 图片可以定义拉伸区域,自动地根据所需的宽高进行相应的缩放并保证不失真。

Nine-Patch File

XML Nine-Patch

<?xml version="1.0" encoding="utf-8"?>
<nine-patch
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/drawable_resource"
    android:dither=["true" | "false"] />

Layer List

LayerDrawable

A LayerDrawable is a drawable object that manages an array of other drawables. Each drawable in the list is drawn in the order of the list—the last drawable in the list is drawn on top.

LayerDrawable 表示一种层次化的 Drawable 集合,通过将不同的 Drawable 放置在不同的 层面上从而达到一种叠加后的效果。

一个 <layer-list> 中可以包含多个 <item> ,每个 <item> 表示一个 drawable 。

<item> 中,可以通过 android:drawable 属性来直接引用一个已有的 Drawable,也可以在 <item> 中自定义 Drawable(例如: <shape>)。

LayerDrawable 有层次的概念,下面的 drawable 会覆盖上面的 drawable 。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/drawable_resource"
        android:id="@+id/resource_name"
        android:top="dimension"
        android:right="dimension"
        android:bottom="dimension"
        android:left="dimension" />
</layer-list>

android:top
Integer. The top offset in pixels.

android:right
Integer. The right offset in pixels.

android:bottom
Integer. The bottom offset in pixels.

android:left
Integer. The left offset in pixels.

默认情况下,所有的 drawable 都会被缩放以适应容器大小:

<item android:drawable="@drawable/image" />

使用 <bitmap> 标签,设置 android:gravity" 属性可以控制图片的显示效果:

<item>
  <bitmap android:src="@drawable/image"
          android:gravity="center" />
</item>

EXAMPLE:

XML file saved at res/drawable/layers.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/android_red"
        android:gravity="center" />
    </item>
    <item android:top="10dp" android:left="10dp">
      <bitmap android:src="@drawable/android_green"
        android:gravity="center" />
    </item>
    <item android:top="20dp" android:left="20dp">
      <bitmap android:src="@drawable/android_blue"
        android:gravity="center" />
    </item>
</layer-list>

Notice that this example uses a nested element to define the drawable resource for each item with a “center” gravity. This ensures that none of the images are scaled to fit the size of the container, due to resizing caused by the offset images.

This layout XML applies the drawable to a View:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/layers" />

The result is a stack of increasingly offset images:


State List

StateListDrawable

A StateListDrawable is a drawable object defined in XML that uses a several different images to represent the same graphic, depending on the state of the object. For example, a Button widget can exist in one of several different states (pressed, focused, or neither) and, using a state list drawable, you can provide a different background image for each state.

You can describe the state list in an XML file. Each graphic is represented by an <item>element inside a single <selector> element. Each <item> uses various attributes to describe the state in which it should be used as the graphic for the drawable.

During each state change, the state list is traversed top to bottom and the first item that matches the current state is used—the selection is not based on the “best match,” but simply the first item that meets the minimum criteria of the state.

StateListDrawable 是在XML中定义的 Drawable 集合,每个 Drawable 都对应着 View 的一种状态,系统会根据 View 的状态来选择合适的 Drawable 。StateListDrawable 主要用于设置可以单击的 View 的 Background。最常见的是 Button。

在状态变化过程中,系统会根据 View 当前的状态从<selector>中选择相应的<item>,每个 item 都对应着一个具体的 Drawable,系统按照从上到下的顺序查找,直到找到第一个匹配的 item 。该选择并非基于“best match”,而仅仅是一个满足该状态的最低标准的第一个 item。

一般情况下,默认的 item 都应该放在 selector 的最后并且不附带任何的状态,这样当上面的 item 都无法匹配 View 的当前状态时,系统就会选择默认的 item。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize=["true" | "false"]
    android:dither=["true" | "false"]
    android:variablePadding=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>
selector标签

Required. This must be the root element. Contains one or more <item> elements.

android:constantSize

Boolean. “true” if the drawable’s reported internal size remains constant as the state changes (the size is the maximum of all of the states); “false” if the size varies based on the current state. Default is false.

如果状态改变时,不同状态下 drawable 的大小是否相同
+ true:各个状态大小相同(取最大的)
+ false:各个状态的大小各自不同。(默认为false )

android:dither

Boolean. “true” to enable dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen (for instance, an ARGB 8888 bitmap with an RGB 565 screen); “false” to disable dithering. Default is true.

如果图片与屏幕的像素配置不一致时,是否开启抖动效果.
+ true:开启抖动效果。(默认为true)
+ false:不开启抖动效果

开启抖动效果,可以让图片能保持较好的显示效果。(建议开启)

android:variablePadding

Boolean. “true” if the drawable’s padding should change based on the current state that is selected; “false” if the padding should stay the same (based on the maximum padding of all the states). Enabling this feature requires that you deal with performing layout when the state changes, which is often not supported. Default is false.

如果状态改变时,不同状态下 drawable 的内边距是否变化
+ true:内边距会根据状态的变化而变化,
+ false:内边距保持一致,取最大的内边距。(默认为false )

设置为true时,你必须为不同的状态配置layout,但是通常不建议这么做。

item标签

Defines a drawable to use during certain states, as described by its attributes. Must be a child of a <selector> element.

android:drawable:为当前控件指定资源

Drawable resource. Required. Reference to a drawable resource.

android:state_pressed:是否按下

Boolean. “true” if this item should be used when the object is pressed (such as when a button is touched/clicked); “false” if this item should be used in the default, non-pressed state.

true表示当用户点击或者触摸该控件的状态。默认为false

android:state_focused: 是否获得焦点

Boolean. “true” if this item should be used when the object has input focus (such as when the user selects a text input); “false” if this item should be used in the default, non-focused state.

ture表示当前控件获得焦点时的状态。默认为false

android:state_hovered: 光标是否悬停

Boolean. “true” if this item should be used when the object is being hovered by a cursor; “false” if this item should be used in the default, non-hovered state. Often, this drawable may be the same drawable used for the “focused” state. Introduced in API level 14.

true表示光标移动到当前控件上的状态。默认为false

android:state_selected: 是否被选择

Boolean. “true” if this item should be used when the object is the current user selection when navigating with a directional control (such as when navigating through a list with a d-pad); “false” if this item should be used when the object is not selected.
The selected state is used when focus (android:state_focused) is not sufficient (such as when list view has focus and an item within it is selected with a d-pad).

true表示被选择的状态。

selected是focus不充分的情况。比如一个listview获得焦点(focus),而用方向键选择了其中的一个item(selected)

android:state_checkable: 是否能被勾选

Boolean. “true” if this item should be used when the object is checkable; “false” if this item should be used when the object is not checkable. (Only useful if the object can transition between a checkable and non-checkable widget.)

ture表示可以被勾选的状态。

这个属性仅在控件能在被勾选和不被勾选的状态间转换时才起作用。(比如RadioButton)

android:state_checked: 是否被勾选

Boolean. “true” if this item should be used when the object is checked; “false” if it should be used when the object is un-checked.

true表示当前控件处于被勾选(check)的状态。

android:state_enabled: 是否可用

Boolean. “true” if this item should be used when the object is enabled (capable of receiving touch/click events); “false” if it should be used when the object is disabled.

true表示当前控件处于可用的状态。比如能够接受触摸或点击事件

android:state_activated: 是否被激活

Boolean. “true” if this item should be used when the object is activated as the persistent selection (such as to “highlight” the previously selected list item in a persistent navigation view); “false” if it should be used when the object is not activated. Introduced in API level 11.

true表示当前控件被激活的状态。

android:state_window_focused: 是否在前台

Boolean. “true” if this item should be used when the application window has focus (the application is in the foreground), “false” if this item should be used when the application window does not have focus (for example, if the notification shade is pulled down or a dialog appears).

true表示当前控件处于前台,应用窗口获得焦点的状态。

Note: Remember that Android applies the first item in the state list that matches the current state of the object. So, if the first item in the list contains none of the state attributes above, then it is applied every time, which is why your default value should always be last (as demonstrated in the following example).

Android 会选择第一个和当前状态匹配的 item ,如果 state list 中的第一个 item 不包含有任何状态,那么这个 item 每次都会匹配成功,从而被系统使用。因此,默认状态总是放在最后。

Example

XML file saved at res/drawable/button.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:state_hovered="true"
          android:drawable="@drawable/button_focused" /> <!-- hovered -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>

This layout XML applies the state list drawable to a Button:

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/button" />

Level List

LevelListDrawable

A Drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Setting the level value of the drawable with setLevel() loads the drawable resource in the level list that has a android:maxLevel value greater than or equal to the value passed to the method.

LevelListDrawable 表示一个 Drawable 集合,集合中的每个 Drawable 都有一个 level(等级)。根据不同的 level ,LevelListDrawable 会切换为对应的 Drawable。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<level-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/drawable_resource"
        android:maxLevel="integer"
        android:minLevel="integer" />
</level-list>

每个 item 表示一个 Drawable ,并且有对应的等级范围,在最小值和最大值之间的等级会对应此 item 中的 Drawable。

android:maxLevel
Integer. The maximum level allowed for this item.

android:minLevel
Integer. The minimum level allowed for this item.

EXAMPLE:

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/status_off"
        android:maxLevel="0" />
    <item
        android:drawable="@drawable/status_on"
        android:maxLevel="1" />
</level-list>

Once this is applied to a View, the level can be changed with setLevel() or setImageLevel().

如果它被作为 View 的背景时,可以通过 setLevel() 方法来设置不同的 level 从而切换到具体的 Drawable。如果它被作为 ImageView 的前景 Drawable 时,还可以通过ImageView 的 setImageLevel() 方法来切换 Drawable。

Drawable 的等级是有范围的(0~10000),最小等级是 0(默认值),最大等级是 10000.


Transition Drawable

TransitionDrawable

A TransitionDrawable is a drawable object that can cross-fade between the two drawable resources.

Each drawable is represented by an <item> element inside a single <transition>element. No more than two items are supported. To transition forward, call startTransition(). To transition backward, call reverseTransition().

TransitionDrawable 用于实现两个 Drawable 之间的淡入淡出效果。

通过startTransition()reverseTransition()方法可以实现淡入淡出效果以及它的逆向过程。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<transition
xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/drawable_resource"
        android:id="@[+]id/resource_name"
        android:top="dimension"
        android:right="dimension"
        android:bottom="dimension"
        android:left="dimension" />
</transition>

EXAMPLE:

XML file saved at res/drawable/transition.xml:

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/on" />
    <item android:drawable="@drawable/off" />
</transition>

This layout XML applies the drawable to a View:

<ImageButton
    android:id="@+id/button"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/transition" />

And the following code performs a 500ms transition from the first item to the second:

ImageButton button = (ImageButton) findViewById(R.id.button);
TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
drawable.startTransition(500);

Inset Drawable

InsetDrawable

A drawable defined in XML that insets another drawable by a specified distance. This is useful when a View needs a background that is smaller than the View’s actual bounds.

InsetDrawable 可以将其他 Drawable 内嵌到自己当中,并可以在四周留出一定的间距。当一个 View 希望自己的 Background 比 自己的实际区域小的时候,可以采用 InsetDrawable 来实现。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<inset
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/drawable_resource"
    android:insetTop="dimension"
    android:insetRight="dimension"
    android:insetBottom="dimension"
    android:insetLeft="dimension" />

android:insetTop、 android:insetBottom、 android:insetLeft、 android:insetRight分别表示顶部、底部、左边右边内凹的大小。

android:insetTop
Dimension. The top inset, as a dimension value or dimension resource

android:insetRight
Dimension. The right inset, as a dimension value or dimension resource

android:insetBottom
Dimension. The bottom inset, as a dimension value or dimension resource

android:insetLeft
Dimension. The left inset, as a dimension value or dimension resource

EXAMPLE:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/background"
    android:insetTop="10dp"
    android:insetLeft="10dp" />

Clip Drawable

ClipDrawable

A drawable defined in XML that clips another drawable based on this Drawable’s current level. You can control how much the child drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars.

ClipDrawable 可以根据自己当前的 level (等级)来裁剪另一个 Drawable,裁剪方向可以通过android:clipOrientationandroid:gravity这两个属性来共同控制。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<clip
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/drawable_resource"
    android:clipOrientation=["horizontal" | "vertical"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |"fill_vertical" | "center_horizontal" | "fill_horizontal" |"center" | "fill" | "clip_vertical" | "clip_horizontal"] />

android:clipOrientation:裁剪方向
Keyword. The orientation for the clip.

ValueDescription
horizontalClip the drawable horizontally.
verticalClip the drawable vertically.

android:gravity
Keyword. Specifies where to clip within the drawable.

EXAMPLE:

XML file saved at res/drawable/clip.xml:

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/android"
    android:clipOrientation="horizontal"
    android:gravity="left" />

The following layout XML applies the clip drawable to a View:

<ImageView
    android:id="@+id/image"
    android:background="@drawable/clip"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content" />

The following code gets the drawable and increases the amount of clipping in order to progressively reveal the image:

ImageView imageview = (ImageView) findViewById(R.id.image);
ClipDrawable drawable = (ClipDrawable) imageview.getDrawable();
drawable.setLevel(drawable.getLevel() + 1000);

Increasing the level reduces the amount of clipping and slowly reveals the image. Here it is at a level of 7000:

Note: The default level is 0, which is fully clipped so the image is not visible. When the level is 10,000, the image is not clipped and completely visible.

Drawable 的等级是有范围的(0~10000),最小等级是 0(默认值),最大等级是 10000。

对于 ClipDrawable 来说,等级 0 表示完全裁剪,即整个 Drawable 都不可见了,而等级 10000 表示不裁剪。


Scale Drawable

ScaleDrawable

A drawable defined in XML that changes the size of another drawable based on its current level.

ScaleDrawable 可以根据自己的 level (等级)将指定的 Drawable 缩放到一定比例。

对于 ScaleDrawable 来说,level 0 表示完全不可见(默认值)。要想 ScaleDrawable 可见,需要等级不能为 0。可以查看 ScaleDrawable 的源码:

public void draw(Canvas canvas) {
    if (mScaleState.mDrawable.getLevel() != 0)
        mScaleState.mDrawable.draw(canvas);
}

ScaleDrawable 的等级和 mDrawable 的等级是保持一致的,所以如果 ScaleDrawable 的等级为 0 ,那么它内部的 mDrawable 的等级也必然为 0 ,这时 mDrawable 就无法绘制出来,也就是 ScaleDrawable 不可见。

protected void onBoundsChange(Rect bounds) {
    final Rect r = mTmpRect;
    final boolean min = mScaleState.mUseIntrinsicSizeAsMin;
    int level = getLevel();
    int w = bounds.width();
    if (mScaleState.mScaleWidth > 0) {
        final int iw = min ? mScaleState.mDrawable.getIntrinsicWidth() : 0;
        w -= (int) ((w - iw) * (10000 - level) * mScaleState.mScaleWidth / 10000);
    }
    int h = bounds.height();
    if (mScaleState.mScaleHeight > 0) {
        final int ih = min ? mScaleState.mDrawable.getIntrinsicHeight() : 0;
        h -= (int) ((h - ih) * (10000 - level) * mScaleState.mScaleHeight / 10000);
    }
    final int layoutDirection = getLayoutDirection();
    Gravity.apply(mScaleState.mGravity, w, h, bounds, r, layoutDirection);

    if (w > 0 && h > 0) {
        mScaleState.mDrawable.setBounds(r.left, r.top, r.right, r.bottom);
    }
}

在 onBoundsChange 方法中可以看出 mDrawable 的大小和等级以及缩放比例的关系。例如,缩放的宽度:

final int iw = min ? mScaleState.mDrawable.getIntrinsicWidth() : 0;
w -= (int) ((w - iw) * (10000 - level) * mScaleState.mScaleWidth / 10000);

由于 iw 一般都为0,所以上面的代码可以简化为:

w -= (int) (w * (10000 - level) * mScaleState.mScaleWidth / 10000);

由此可见:
如果 ScaleDrawable 的 level 是 10000,那么就没有缩放的效果。
如果 ScaleDrawable 的 level 越大,那么缩放效果就越小,内部的 Drawable 看起来就越大。
如果 ScaleDrawable 在 XML 中定义的缩放比例(android:scaleWidth)越大,那么缩放效果就越大,内部的 Drawable 看起来就越小。

从 ScaleDrawable 的内部实现来看, ScaleDrawable 的作用更偏向于缩小一个特定的 Drawable 。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<scale
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/drawable_resource"
    android:scaleGravity=["top" | "bottom" | "left" | "right" | "center_vertical" |"fill_vertical" | "center_horizontal" | "fill_horizontal" | "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:scaleHeight="percentage"
    android:scaleWidth="percentage" />

android:scaleHeight:高度缩放比例

Percentage. The scale height, expressed as a percentage of the drawable’s bound. The value’s format is XX%. For instance: 100%, 12.5%, etc.

android:scaleWidth:宽度缩放比例

Percentage. The scale width, expressed as a percentage of the drawable’s bound. The value’s format is XX%. For instance: 100%, 12.5%, etc.

android:scaleGravity

Keyword. Specifies the gravity position after scaling.
Must be one or more (separated by ‘|’) of the following constant values:

类似于android:gravity

EXAMPLE:

近似地将一张图片缩小为原来的20%,代码如下所示:
res/drawable/scale_drawable.xml:

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/logo"
    android:scaleGravity="center_vertical|center_horizontal"
    android:scaleHeight="80%"
    android:scaleWidth="80%" />

直接使用上面的 drawable 资源是不行的,还必须设置 ScaleDrawable 的等级(0~10000),如下所示:

View testScale = findViewById(R.drawable.test_scale);
ScaleDrawable testScaleDrawable = (ScaleDrawable)testScale.getBackground();
testScaleDrawable.setLevel(1);

经过上面的两步就可以正确地缩放一个 Drawable,如果少了设置 level 这一步骤,由于 Drawable 的默认等级为 0 ,那么 ScaleDrawable 将无法显示出来。


Shape Drawable

ShapeDrawable
GradientDrawable

An XML file that defines a geometric shape, including colors and gradients. Creates a ShapeDrawable.

ShapeDrawable 是一种很常见的 Drawable,可以理解为通过颜色来构造的图形,它既可以是纯色的图形,也可以是具有渐变效果的图形。

<shpae>标签创建的 Drawable ,其实体类实际上是 GradientDrawable。

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape=["rectangle" | "oval" | "line" | "ring"] >
    <corners
        android:radius="integer"
        android:topLeftRadius="integer"
        android:topRightRadius="integer"
        android:bottomLeftRadius="integer"
        android:bottomRightRadius="integer" />
    <gradient
        android:angle="integer"
        android:centerX="integer"
        android:centerY="integer"
        android:centerColor="integer"
        android:endColor="color"
        android:gradientRadius="integer"
        android:startColor="color"
        android:type=["linear" | "radial" | "sweep"]
        android:useLevel=["true" | "false"] />
    <padding
        android:left="integer"
        android:top="integer"
        android:right="integer"
        android:bottom="integer" />
    <size
        android:width="integer"
        android:height="integer" />
    <solid
        android:color="color" />
    <stroke
        android:width="integer"
        android:color="color"
        android:dashWidth="integer"
        android:dashGap="integer" />
</shape>

ELEMENTS:

shape标签

The shape drawable. This must be the root element.

android:shape:形状
Keyword. Defines the type of shape.

ValueDesciption含义
“rectangle”A rectangle that fills the containing View. This is the default shape.矩形
“oval”An oval shape that fits the dimensions of the containing View.椭圆
“line”A horizontal line that spans the width of the containing View. This shape requires the <stroke> element to define the width of the line.横线
“ring”A ring shape.圆环

The following attributes are used only when android:shape=”ring”:

android:innerRadius:内环的半径

Dimension. The radius for the inner part of the ring (the hole in the middle), as a dimension value or dimension resource.

尺寸, 内环的半径。一个尺寸值(dip等等)或者一个尺寸资源。
和 android:innerRadiusRatio 同时存在,以 android:innerRadius 为准。

android:innerRadiusRatio

Float. The radius for the inner part of the ring, expressed as a ratio of the ring’s width. For instance, if android:innerRadiusRatio=”5”, then the inner radius equals the ring’s width divided by 5. This value is overridden by android:innerRadius. Default value is 9.

Float类型,这个值表示内部环的比例。默认值是9。
例如,如果 android:innerRadiusRatio = ” 5 ” ,那么内环的半径等于环的宽度除以5。

android:thickness:圆环的厚度

Dimension. The thickness of the ring, as a dimension value or dimension resource.

尺寸,圆环的厚度。是一个尺寸值或尺寸的资源。即外半径减去内半径的大小。
和 android:thicknessRatio同时存在,以 android:thickness为准。

android:thicknessRatio

Float. The thickness of the ring, expressed as a ratio of the ring’s width. For instance, if android:thicknessRatio=”2”, then the thickness equals the ring’s width divided by 2. This value is overridden by android:innerRadius. Default value is 3.

Float类型,圆环厚度的比例。默认值是3。
例如,如果android:thicknessRatio= ” 2 “,然后厚度等于环的宽度除以2。

android:useLevel

Boolean. “true” if this is used as a LevelListDrawable. This should normally be “false” or your shape may not appear.

Boolean类型。如果用在 LevelListDrawable 里,那么就是true。其他情况下一般为false。

corners:圆角效果

Creates rounded corners for the shape. Applies only when the shape is a rectangle.

为 Shape 创建一个圆角,只适用于 rectangle (矩形)。

android:radius:角度

Dimension. The radius for all corners, as a dimension value or dimension resource. This is overridden for each corner by the following attributes.

Dimension,圆角的半径。为四个角同时设定相同的角度,会被其他圆角属性覆盖。

android:topLeftRadius:左上角的角度

Dimension. The radius for the top-left corner, as a dimension value or dimension resource.

Dimension,top-left 设置左上角的半径

android:topRightRadius:右上角的角度

Dimension. The radius for the top-right corner, as a dimension value or dimension resource.

Dimension,top-right 设置右上角的半径

android:bottomLeftRadius:左下角的角度

Dimension. The radius for the bottom-left corner, as a dimension value or dimension resource.

Dimension,设置右下角的半径

android:bottomRightRadius:右下角的角度

Dimension. The radius for the bottom-right corner, as a dimension value or dimension resource.

Dimension,设置右下角的半径

Note: Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero (“0dp”) where you don’t want rounded corners.

gradient:渐变效果

Specifies a gradient color for the shape.

指定 shape 的渐变颜色。与 <solid> 标签是互斥的,solid 表示纯色填充,gradient 表示渐变效果。

android:angle:渐变的角度

Integer. The angle for the gradient, in degrees. 0 is left to right, 90 is bottom to top. It must be a multiple of 45. Default is 0.

Integer,渐变的角度。 (默认为0)
0 代表从 left 到 right。90 代表 bottom 到 top。必须是45的倍数

android:centerX:渐变的中心点的横坐标

Float. The relative X-position for the center of the gradient (0 - 1.0).

Float,渐变中心的X坐标,在0到1.0之间。

android:centerY:渐变的中心点的纵坐标

Float. The relative Y-position for the center of the gradient (0 - 1.0).

Float,渐变中心的相对X坐标,在0到1.0之间。
渐变的中心点会影响渐变的具体效果。

android:startColor:起始颜色

Color. The starting color, as a hexadecimal value or color resource.

Color,开始的颜色值。

android:endColor:结束颜色

Color. The ending color, as a hexadecimal value or color resource.

Color,结束的颜色。

android:centerColor:中间颜色

Color. Optional color that comes between the start and end colors, as a hexadecimal value or color resource.

Color,可选的颜色值。基于startColor和endColor之间。

android:gradientRadius:渐变的半径

Float. The radius for the gradient. Only applied when android:type=”radial”.

Float ,渐变的半径。仅当 android:type=”radial” 时才有效。

android:type:渐变的类型

Keyword. The type of gradient pattern to apply. Valid values are:

Keyword,渐变的模式:

ValueDescription含义
“linear”A linear gradient. This is the default.线性渐变
“radial”A radial gradient. The start color is the center color.径向渐变
“sweep”A sweeping line gradient.扫描渐变

android:useLevel

Boolean. “true” if this is used as a LevelListDrawable.

Boolean,如果在 LevelListDrawable 中使用,则为true。

padding:内边距

Padding to apply to the containing View element (this pads the position of the View content, not the shape).

内边距,内容与 View 边界的距离

android:left

Dimension. Left padding, as a dimension value or dimension resource.

Dimension,左边填充距离.

android:top

Dimension. Top padding, as a dimension value or dimension resource.

Dimension,顶部填充距离.

android:right

Dimension. Right padding, as a dimension value or dimension resource.

Dimension,右边填充距离.

android:bottom

Dimension. Bottom padding, as a dimension value or dimension resource.

Dimension,底部填充距离.

size:大小

The size of the shape.

android:height

Dimension. The height of the shape, as a dimension value or dimension resource.

android:width

Dimension. The width of the shape, as a dimension value or dimension resource.

表示的是 shape 的固有大小,但是一般情况下并不是 shape 最终显示的大小。
对于 shape 来说,它本身并没有宽高的概念,作为 View 的 Background 它会自适应 View 的宽高。

Note: The shape scales to the size of the container View proportionate to the dimensions defined here, by default. When you use the shape in an ImageView, you can restrict scaling by setting the android:scaleType to “center”.

默认情况下,shape 会缩放进行适当的缩放。当你在一个ImageView中使用shape 时,可以使用 android:scaleType=”center” 来限制缩放。

solid:纯色填充

A solid color to fill the shape.
填充shape的纯色

android:color

Color. The color to apply to the shape, as a hexadecimal value or color resource.

Color,颜色值,十六进制数,或者一个Color资源

stroke:描边效果

A stroke line for the shape.

shape使用的笔画,当android:shape=”line”的时候,必须设置该标签来指定线的宽度和颜色等信息。

android:width:描边的宽度

Dimension. The thickness of the line, as a dimension value or dimension resource.

Dimension,笔画的粗细。

android:color:描边的颜色

Color. The color of the line, as a hexadecimal value or color resource.

Color,笔画的颜色

android:dashGap:组成虚线的线段之间的间隔

Dimension. The distance between line dashes, as a dimension value or dimension resource. Only valid if android:dashWidth is set.

Dimension,每画一条线就间隔多少。只有当 android:dashWidth 也设置了才有效。

android:dashWidth:组成虚线的线段的宽度

Dimension. The size of each dash line, as a dimension value or dimension resource. Only valid if android:dashGap is set.

Dimension,每画一条线的长度。只有当 android:dashGap 也设置了才有效。

android:dashGap 和 android:dashWidth 设置这条线为虚线的,其中 android:dashWidth 表示 “-” 这样一个横线的宽度,android:dashGa p表示之间隔开的距离。

EXAMPLE:

XML file saved at res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

This layout XML applies the shape drawable to a View:

<TextView
    android:background="@drawable/gradient_box"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content" />

This application code gets the shape drawable and applies it to a View:

Resources res = getResources();
Drawable shape = res. getDrawable(R.drawable.gradient_box);

TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值