XML文件中的shape节点详解

本文介绍如何利用Android中的ShapeDrawable来定制视图样式,包括实现填充、渐变、描边、圆角等效果,并提供了具体的XML配置示例。
当我们开发中,经常用到Shape Drawable(shape节点)。shape是用来定义形状的。

XML文件中的shape节点,我们举一个代码示例:

XML 文件保存在 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">
    <!-- shape:指定的形状,rectangle(矩形,默认)、oval(椭圆)、line(线型的)、ring(环形的)-->
    <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>


以下为shape的一些常见属性

1、solid:实心,就是填充的意思      android:color指定填充的颜色   
2、gradient:渐变       android:startColor和android:endColor分别为起始和结束颜色,android:angle是渐变角度,必须为45的整数倍当angle=0时,渐变色是从左向右。 然后逆时针方向转,当angle=90时为从下往上。另外渐变默认的模式为android:type="linear",即线性渐变,可以指定渐变为径向渐变,android:type="radial",径向渐变需要指定半径android:gradientRadius="50",也可一指定二者的综合,扫描渐变 android: type="sweep"    
3、stroke:描边     android:width="2dp" 描边的宽度,android:color 描边的颜色。我们还可以把描边弄成虚线的形式,设置方式为:android:dashWidth="5dp"  android:dashGap="3dp" 其中android:dashWidth表示'-'这样一个横线的宽度,android:dashGap表示之间隔开的距离。      
4、corners:圆角      android:radius为角的弧度,值越大角越圆。我们还可以把四个角设定成不同的角度,方法为:
android:topRightRadius="8dp" 右上角
android:bottomLeftRadius="10dp" 左下角 
android:topLeftRadius="1dp" 左上角
android:bottomRightRadius="5dp" 右下角     
5、panding:内边矩 


让这个XML用到一个View上:

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

让这个XML用java代码用到一个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、付费专栏及课程。

余额充值