Android shape

本文详细介绍了如何使用XML定义各种形状,包括矩形、椭圆、线条和环状,并解释了如何设置边角、填充样式、边框效果等属性。通过这些配置可以实现复杂的图形界面设计。
<?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>
Android开发中,Shape可用于定义各种形状和图片资源,使用它能减少资源占用、缩小安装包大小,还可适配不同尺寸手机[^1]。 ### 使用方法 在res/drawable目录下创建一个XML文件来定义Shape。例如,创建一个名为`custom_shape.xml`的文件: ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 形状类型,这里是矩形 --> <solid android:color="#FF0000" /> <!-- 填充颜色 --> <stroke android:width="2dp" android:color="#000000" /> <!-- 边框宽度和颜色 --> <corners android:radius="10dp" /> <!-- 圆角半径 --> <size android:width="200dp" android:height="100dp" /> <!-- 大小 --> </shape> ``` 然后在布局文件中使用这个Shape作为视图的背景: ```xml <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/custom_shape" android:text="Hello, Shape!" /> ``` ### 相关属性 - **形状类型(`android:shape`)**:取值有`rectangle`(矩形)、`oval`(椭圆)、`line`(线)、`ring`(圆环)。 - **填充颜色(`solid`)**:`<solid android:color="#颜色值" />`用于设置形状的填充颜色。 - **边框(`stroke`)**: - `android:width`:边框宽度。 - `android:color`:边框颜色。 - 还可以设置`android:dashWidth`和`android:dashGap`来创建虚线边框。 - **圆角(`corners`)**: - `android:radius`:统一设置四个角的圆角半径。 - 也可以分别设置每个角的半径,如`android:topLeftRadius`等。 - **大小(`size`)**:`android:width`和`android:height`用于设置Shape的大小。 若在XML里已将`BackGround`设为Shape属性,在代码中设置`BackGround`会覆盖Shape属性。若要保证Shape属性不变又能切换颜色,可定义多个`shape.xml`文件来实现[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值