Android基础学习-Drawable

在这里插入图片描述

Drawable资源使用注意事项

 - Drawable分为两种: 一种是我们普通的图片资源直接导入res/mipmap或res/Drawable-xxdpi中, 另一种是我们编写的XML形式的Drawable资源,一般把它们放到res/drawable目录下;
 -XML我们直接通过@mipmap或者@drawable设置Drawable即可 比如: android:background="@mipmap/login_bind_phone" android:background="@drawable/button44_shape" android:src="@drawable/primaryvip" 而在Java代码中我们可以通过Resource的getDrawable(R.mipmap.xxx)可以获得drawable资源 如果是为某个控件设置背景,比如ImageView,我们可以直接调用控件.getDrawale()同样 可以获得drawable对象!
 - Android中drawable中的资源名称有约束,必须是:[a-z0-9_.](即:只能是字母数字及和.), 而且不能以数字开头,否则编译会报错: Invalid file name: must contain only [a-z0-9.]! 注意一定是小写哦 小写!!!小写!!!

1.ColorDrawable
代码中定义ColorDrawable:
TextView textView1 = (TextView)findViewById(R.id.textView1);
ColorDrawable drawable = new ColorDrawable(0xffff2200);
textView1.setBackground(drawable);

TextView textView2 = (TextView)findViewById(R.id.textView2);
textView2.setTextColor(Resources.getSystem().getColor(R.color.purple_200));
textView2.setBackground(getDrawable(R.drawable.flower));

大多数时候是在res/values目录下创建colors.xml文件,把需要用到的颜色值写在里面 通过@color获取
colors.xml文件:系统创建自动生成的颜色我们只需把需要的往里面添加就行系统生成的可以去掉
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>

xml文件中引用:
<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ColorDrawable"
        android:textColor="@color/purple_500"
        android:textSize="20dp"
        android:background="@color/purple_200"/>

其他方法:
java中设置颜色值:
TextView textView = (TextView) findViewById(R.id.textView);
int mycolor = getResources().getColor(R.color.mycolor);
textView.setBackgroundColor(mycolor);
或下面方法获取
int systemColor = Resources.getSystem().getColor(R.color.mycolor);
int argbColor = Color.argb(0xff, 0x00, 0x00, 0x00);
int parseColor = Color.parseColor("#FF3333");

Kotlin中设置颜色值:
val textView = findViewById<TextView>(R.id.textView)
textView.setTextColor(resources.getColor(R.color.mycolor)) //注意是否过期否则用下面的方法
textView.setTextColor(ContextCompat.getColor(this, R.color.mycolor))

val argbColor = Color.argb(0xff, 0x00, 0x00, 0x00)
val parseColor = Color.parseColor("#FF3333")

2.NiewPatchDrawable

(九妹)图片
1.点9图不能放在mipmap目录下,而需要放在drawable目录下!
2.编辑图片时留出不能拉伸的图形,处理设置图片拉伸区域

<!--pic9.xml-->  
<!--参数依次为:引用的.9图片,是否对位图进行抖动处理-->  
<?xml version="1.0" encoding="utf-8"?>  
<nine-patch  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:src="@drawable/dule_pic"  
    android:dither="true"/>  
  
<!--参数依次为:引用的.9图片,是否对位图进行抖动处理-->  
<?xml version="1.0" encoding="utf-8"?>  
<bitmap  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:src="@drawable/dule_pic"  
    android:dither="true"/>

3.ShapeDrawable
<shape>:
~ visible:设置是否可见
~ shape:形状,可选:rectangle(矩形,包括正方形),oval(椭圆,包括圆),line(线段),ring(环形)
~ innerRadiusRatio:当shape为ring才有效,表示环内半径所占半径的比率,如果设置了innerRadius, 他会被忽略
~ innerRadius:当shape为ring才有效,表示环的内半径的尺寸
~ thicknessRatio:当shape为ring才有效,表环厚度占半径的比率
~ thickness:当shape为ring才有效,表示环的厚度,即外半径与内半径的差
~ useLevel:当shape为ring才有效,表示是否允许根据level来显示环的一部分
②<size>:
~ width:图形形状宽度
~ height:图形形状高度
③<gradient>:后面GradientDrawable再讲~<solid>
~ color:背景填充色,设置solid后会覆盖gradient设置的所有效果!!!!!!<stroke>
~ width:边框的宽度
~ color:边框的颜色
~ dashWidth:边框虚线段的长度
~ dashGap:边框的虚线段的间距
⑥<conner>
~ radius:圆角半径,适用于上下左右四个角
~ topLeftRadius,topRightRadius,BottomLeftRadius,tBottomRightRadius: 依次是左上,右上,左下,右下的圆角值,按自己需要设置!<padding>
        left,top,right,bottm:依次是左上右下方向上的边距!

详情见 Android基础学习-shape篇

4.GradientDrawable

一个具有渐变区域的Drawable,可以实现线性渐变,发散渐变和平铺渐变效果 核心节点:,有如下可选属性:

startColor:渐变的起始颜色
centerColor:渐变的中间颜色
endColor:渐变的结束颜色
type:渐变类型,可选(linear,radial,sweep), 线性渐变(可设置渐变角度),发散渐变(中间向四周发散),平铺渐变
centerX:渐变中间亚瑟的x坐标,取值范围为:0~1
centerY:渐变中间颜色的Y坐标,取值范围为:0~1
angle:只有linear类型的渐变才有效,表示渐变角度,必须为45的倍数哦
gradientRadius:只有radial和sweep类型的渐变才有效,radial必须设置,表示渐变效果的半径
useLevel:判断是否根据level绘制渐变效果

具体用法渐变参照Android基础学习-shape篇

5.BitmapDrawable

Bitmap的一种封装,可以设置它包装的bitmap在BitmapDrawable区域中的绘制方式,有: 平铺填充,拉伸填或保持图片原始大小!以为根节点! 可选属性如下:

android:src:图片资源~位图文件的标识符。 该属性是强制性的。可以以“@ [+] [package] type / name”格式或以“?[package] type / name”形式的另一个资源的引用。可以是“#rgb”,“#argb”,“#rrggbb”或“#aarrggbb”形式的颜色值。
android:antialias:是否支持抗锯齿启用或禁用抗锯齿。 旋转时,可以使用抗锯齿来平滑位图的边缘。 默认值是false。开启后会让图片变得光滑,但是可以忽略的降低图片的清晰度。
android:filter:是否支持位图过滤,支持的话可以是图批判显示时比较光滑;启用或禁用位图过滤。 当位图缩小或拉伸以平滑其外观时,将使用过滤。 默认值为true。当图片尺寸被拉伸或者被压缩时候,可以较好的保持显示
android:dither:是否对位图进行抖动处理,如果位图不具有与屏幕相同的像素配置(例如:具有RGB 565屏幕的ARGB 8888位图),则启用或禁用位图抖动。 默认值为true。当图片的像素配置和手机屏幕的像素配置不一致时,开启这个可以让高质量的图片在低质量的屏幕上还有较好的显示效果。
android:gravity:若位图比容器小,可以设置位图在容器中的相对位置,定义位图的重力。 如果位图比容器小,则重力表示绘图在其容器中的位置。必须是以下常量值中的一个或多个(用'|'分隔)
	top:图片放在容器顶部 ,不改变图片大小
	bottom:图片放在容器底部,不改变图片大小
	left:图片放在容器左侧,不改变图片大小
	right:土坯啊您放在容器右侧,不改变图片大小
	center_vertical:是图片竖直居中,不改变图片大小
	fill_vertical:图片竖直方向填充容器
	cennter_horizonntal:使图片水平居中,不改变图片大小
	fill_horizontal:图片水平方向填充容器
	center:使图片在水平和竖直方向上同时居中,不改变图片大小
	fill:图片在水平和竖直方向上填充容器,这是默认值
	clip_vertical:附加选项,竖直方向上裁剪
	clip_horizontal:附加选项,水平方向上裁剪
	start:将图片推到容器的开始位置,而不是改变它的大小。
	end:将图片推到容器的结束位置,而不改变它的大小。
android:tileMode:指定图片平铺填充容器的模式,设置这个的话,gravity属性会被忽略,有以下可选值: disabled(整个图案拉伸平铺),clamp(原图大小复制边缘颜色。图片四周的像素会扩散到周围), repeat(在水平和竖直方向上的平铺效果),mirror(镜像平铺在水平和竖直方向上的镜面投影效果)
android:tileModeX:和上面类似,不过方向变成了只在水平方向
android:tileModeY:和上面类似,不过方向上只在竖直方向

一张图片可以直接去使用,也可以通过XML采用上述属性去描述图片。在布局文件中给View直接设置背景 。

构造方法:
BitmapDrawable ()、BitmapDrawable (Bitmap bitmap)创建一个空的drawable,此方法在API 4的时候被弃用,在API 1中添加
BitmapDrawable(Resources res)创建一个空的drawable,根据资源的显示度量设置初始目标密度。此方法在API 18被弃用
BitmapDrawable (Resources res, Bitmap bitmap) 从位图创建drawable,根据资源的显示度量设置初始目标密度。
BitmapDrawable (String filepath)  通过打开给定的文件路径并解码位图来创建绘图。此方法在API 5 被弃用
BitmapDrawable (Resources res, String filepath) 通过打开给定的文件路径并解码位图来创建绘图。
BitmapDrawable (InputStream is)此方法在API5被弃用
BitmapDrawable (Resources res, InputStream is)通过解码来自给定输入流的位图来创建绘图

XML定义BitmapDrawable:
<?xml version="1.0" encoding="utf-8"?>  
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"  
    android:dither="true"  
    android:src="@drawable/ic_launcher"  
    android:tileMode="mirror" />

②实现相同效果的Java代码:
BitmapDrawable bitDrawable = new BitmapDrawable(bitmap);  
bitDrawable.setDither(true);  
bitDrawable.setTileModeXY(TileMode.MIRROR,TileMode.MIRROR);  

6.InsertDrawable

表示把一个Drawable嵌入到另外一个Drawable的内部,并且在内部留一些间距, 类似与Drawable的padding属性,但padding表示的是Drawable的内容与Drawable本身的边距! 而InsetDrawable表示的是两个Drawable与容器之间的边距,当控件需要的背景比实际的边框 小的时候,比较适合使用InsetDrawable,比如使用这个可以解决我们自定义Dialog与屏幕之间 的一个间距问题,相信做过的朋友都知道,即使我们设置了layout_margin的话也是没用的,这个 时候就可以用到这个InsetDrawable了!只需为InsetDrawable设置一个insetXxx设置不同 方向的边距,然后为设置为Dialog的背景即可!

1.drawable:引用的Drawable,如果为空,必须有一个Drawable类型的子节点!
2.visible:设置Drawable是否额空间
3.insetLeft,insetRight,insetTop,insetBottm:设置左右上下的边距

XML中使用:
<?xml version="1.0" encoding="utf-8"?>  
<inset xmlns:android="http://schemas.android.com/apk/res/android"  
    android:drawable="@drawable/test1"  
    android:insetBottom="10dp"  
    android:insetLeft="10dp"  
    android:insetRight="10dp"  
    android:insetTop="10dp" /> 

在Java代码中使用:
InsetDrawable insetDrawable = new InsetDrawable(getResources()  
insetDrawable.getDrawable(R.drawable.test1), 10, 10, 10, 10); 

7.ClipDrawable

根据设置level的值来决定剪切 区域的大小,根节点是
相关属性:

clipOrietntion:设置剪切的方向,可以设置水平和竖直2个方向
gravity:从那个位置开始裁剪
drawable:引用的drawable资源,为空的话需要有一个Drawable类型的子节点 ps:这个Drawable类型的子节点:就是在<clip里>

①定义一个ClipDrawable的资源xml:
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:clipOrientation="horizontal"
    android:drawable="@mipmap/ic_bg_meizi"
    android:gravity="left" /> 
②在activity_main主布局文件中设置一个ImageView,将src设置为clipDrawable! 记住是src哦,如果你写成了blackground的话可是会报空指针的哦!!!!
 <ImageView
android:id="@+id/img_show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/clip_bg" />

8.RotateDrawable

用来对Drawable进行旋转,也是通过setLevel来控制旋转的,最大值也是:10000

fromDegrees:起始的角度,,对应最低的level值,默认为0
toDegrees:结束角度,对应最高的level值,默认360
pivotX:设置参照点的x坐标,取值为0~1,默认是50%,0.5
pivotY:设置参照点的Y坐标,取值为0~1,默认是50%,0.5 ps:如果出现旋转图片显示不完全的话可以修改上述两个值解决!
drawable:设置位图资源
visible:设置drawable是否可见!

①定义一个rotateDrawable资源文件:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@mipmap/ic_launcher"
    android:fromDegrees="-180"
    android:pivotX="50%"
    android:pivotY="50%" />  
②activity_main.xml中修改下src指向上述drawable即可,MainActivity只需要把ClipDrawable 改成rotateDrawable即可!

9.AnimationDrawable

AnimationDrawable是用来实现Android中帧动画的,就是把一系列的 Drawable,按照一定得顺序一帧帧地播放;Android中动画比较丰富,有传统补间动画,平移, 缩放等等效果,但是这里我们仅仅介绍这个AnimationDrawable实现帧动画,关于alpha,scale, translate,rotate等
使用作为根节点
相关属性:

oneshot:设置是否循环播放,false为循环播放
duration:帧间隔时间,通常我们会设置为300毫秒 我们获得AniamtionDrawable实例后,需要调用它的start()方法播放动画,另外要注意 在OnCreate()方法中调用的话,是没有任何效果的,因为View还没完成初始化,我们可以 用简单的handler来延迟播放动画!

①先定义一个AnimationDrawable的xml资源文件:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item
        android:drawable="@drawable/refresh_loading1"
        android:duration="100" />
    <item
        android:drawable="@drawable/refresh_loading2"
        android:duration="100" />
    <item
        android:drawable="@drawable/refresh_loading3"
        android:duration="100" />
    <item
        android:drawable="@drawable/refresh_loading4"
        android:duration="100" />
    <item
        android:drawable="@drawable/refresh_loading5"
        android:duration="100" />
    <item
        android:drawable="@drawable/refresh_loading6"
        android:duration="100" />
</animation-list> 

②activity_main.xml设置下src,然后MainActivity中:
        ImageView img_show = (ImageView) findViewById(R.id.img_show);
        // 核心实现代码
       AnimationDrawable ad = (AnimationDrawable) img_show.getDrawable();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                ad.start();
            }
        }, 300);

10. LayerDrawable

层图形对象包含一个Drawable数组,然后按照数组对应的顺序来绘制他们,索引值最大的Drawable会被绘制在最上层!虽然这些Drawable会有交叉或者重叠的区域,但 他们位于不同的层,所以并不会相互影响,以作为根节点!
相关属性:

drawable:引用的位图资源,如果为空徐璈有一个Drawable类型的子节点
left:层相对于容器的左边距
right:层相对于容器的右边距
top:层相对于容器的上边距
bottom:层相对于容器的下边距
id:层的id

layerList_one.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid android:color="#C2C2C1" />
            <corners android:radius="50dp" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape android:shape="rectangle">
                <solid android:color="#BCDA73" />
                <corners android:radius="50dp" />
            </shape>
        </clip>
    </item>
</layer-list> 

XML<SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
        android:indeterminateOnly="false"
        android:maxHeight="10dp"
        android:minHeight="5dp"
        android:progressDrawable="@drawable/layerlist_one"
        android:thumb="@drawable/shape_slider" />

层叠图片的layerlist_two.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_bg_ciwei" />
    </item>
    <item
        android:left="25dp"
        android:top="25dp">
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_bg_ciwei" />
    </item>
    <item
        android:left="50dp"
        android:top="50dp">
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_bg_ciwei" />
    </item>
</layer-list> 

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

11.LevelListDrawable

用来管理一组Drawable的,我们可以为里面的drawable设置不同的level, 当他们绘制的时候,会根据level属性值获取对应的drawable绘制到画布上,根节点 为:他并没有可以设置的属性,我们能做的只是设置每个 的属性!
item可供设置的属性如下
注意事项:
1、layer-list可以包含多个item,每个item表示一个drawable,并且后添加的item会覆盖到之前添加的item上面
2、默认情况下,layer-list所有的drawable都会缩放至view大大小,通过设施android:gravity可以调节缩放的效果
3、可以设置上下左右偏移量,android:top、android:bottom、android:left、android:right

drawable:引用的位图资源,如果为空徐璈有一个Drawable类型的子节点
minlevel:level对应的最小值
maxlevel:level对应的最大值

shape_cir1.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#2C96ED"/>
    <size android:height="20dp" android:width="20dp"/>
</shape>

level_cir.xml:
<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/shape_cir1" android:maxLevel="2000"/>
    <item android:drawable="@drawable/shape_cir2" android:maxLevel="4000"/>
    <item android:drawable="@drawable/shape_cir3" android:maxLevel="6000"/>
    <item android:drawable="@drawable/shape_cir4" android:maxLevel="8000"/>
    <item android:drawable="@drawable/shape_cir5" android:maxLevel="10000"/>
</level-list> 

level_cir.xml:
<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/shape_cir1" android:maxLevel="2000"/>
    <item android:drawable="@drawable/shape_cir2" android:maxLevel="4000"/>
    <item android:drawable="@drawable/shape_cir3" android:maxLevel="6000"/>
    <item android:drawable="@drawable/shape_cir4" android:maxLevel="8000"/>
    <item android:drawable="@drawable/shape_cir5" android:maxLevel="10000"/>
</level-list> 

Activity中使用:
public class MainActivity extends AppCompatActivity {
    
    

    private ImageView img_show;
    private LevelListDrawable ld;
    private Handler handler = new Handler() {
    
    
        public void handleMessage(Message msg) {
    
    
            if (msg.what == 0x123) {
    
    
                if (ld.getLevel() > 10000) ld.setLevel(0);
                img_show.setImageLevel(ld.getLevel() + 2000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img_show = (ImageView) findViewById(R.id.img_show);
        ld = (LevelListDrawable) img_show.getDrawable();
        img_show.setImageLevel(0);
        new Timer().schedule(new TimerTask() {
    
    
            @Override
            public void run() {
    
    
                handler.sendEmptyMessage(0x123);
            }
        }, 0, 100);
    }
}

12.StateListDrawable

钮设置不同状态的drawable的用到的就是这个StateListDrawable
相关属性:

drawable:引用的Drawable位图,我们可以把他放到最前面,就表示组件的正常状态~
state_focused:是否获得焦点
state_window_focused:是否获得窗口焦点 当view获取焦点
state_enabled:控件是否可用 当一个view处于可用状态
state_checkable:控件可否被勾选,eg:checkbox
state_checked:控件是否被勾选 当一个view被选中时,适用于CheckBox
state_selected:控件是否被选择,针对有滚轮的情况 当一个view被选择时
state_pressed:控件是否被按下 当按住一个view时,按下的状态
state_active:控件是否处于活动状态,eg:slidingTab
state_single:控件包含多个子控件时,确定是否只显示一个子控件
state_first:控件包含多个子控件时,确定第一个子控件是否处于显示状态
state_middle:控件包含多个子控件时,确定中间一个子控件是否处于显示状态
state_last:控件包含多个子控件时,确定最后一个子控件是否处于显示状态

shape_btn_normal.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#DD788A"/>
    <corners android:radius="5dp"/>
    <padding android:top="2dp" 
             android:bottom="2dp"
             />
</shape>

selctor_btn.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/shape_btn_pressed"
          />
    <item android:drawable="@drawable/shape_btn_normal"/>
</selector>

然后按钮设置android:background="@drawable/selctor_btn"就可以了,可以根据具体需求更改形状(圆形、椭圆...)

13.TransitionDrawable

LayerDrawable的一个子类,TransitionDrawable只管理两层的Drawable!两层!两层! 并且提供了透明度变化的动画,可以控制一层Drawable过度到另一层Drawable的动画效果。 根节点为,记住只有两个Item,多了也没用,属性和LayerDrawable差不多, 我们需要调用startTransition方法才能启动两层间的切换动画; 也可以调用reverseTransition()方法反过来播放:

在res/drawable创建一个TransitionDrawable的xml文件
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@mipmap/ic_bg_meizi1"/>
    <item android:drawable="@mipmap/ic_bg_meizi2"/>
</transition>

布局文件里加个ImageView,然后把src设置成上面的这个drawable
ImageView img_show = (ImageView) findViewById(R.id.img_show);
TransitionDrawable td = (TransitionDrawable) img_show.getDrawable();
td.startTransition(3000);
//你可以可以反过来播放,使用reverseTransition即可~
//td.reverseTransition(3000);

转载:https://blog.csdn.net/oschina_41673164/article/details/127135103

在这里插入图片描述

Drawable资源使用注意事项

猜你喜欢

转载自blog.csdn.net/gqg_guan/article/details/134851477