Android 圆角边框和渐变

本文介绍了如何在Android中创建带有圆角和渐变效果的UI元素。通过在drawable资源文件中定义shapeCorner.xml实现圆角边框,设置不同角的半径以实现圆润效果。同时,通过shapeGradient.xml定义渐变色,调整angle属性来改变颜色过渡方向,并设置startColor、endColor以确定颜色变化范围。最后,将两者结合,为按钮等组件设置这种复合背景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先在res文件夹下的drawable里新建一个文件shape_corner.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/blue" />
    <corners android:topLeftRadius="20dp"
        android:topRightRadius="20dp"
        android:bottomRightRadius="20dp"
        android:bottomLeftRadius="20dp"/>
    <stroke android:width="1dp" android:color="@color/black" />
</shape>

<solidandroid:color>设置了背景颜色。android:topLeftRadius、android:topRightRadius、android:bottomLeftRadius、android:bottomRightRadius分别是左上角、右上角、左下角、右下角的半径值,设置了半径值,相应的角就是圆角,半径值越大,圆角就越大。<stroke>设置边界属性,如边界的宽度、颜色等。

将按钮的背景设置为shape_corner,

android:background="@drawable/shape_corner"

如图:

再来说说渐变,在res的drawable里新建一个文件shape_gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:endColor="@color/colorPrimary"
        android:centerColor="@color/blue"
        android:startColor="@color/colorAccent" />
</shape>

[android:angle]渐变色的角度,举例来说,0代表从上至下颜色渐变;45代表从左至右颜色渐变;90代表从下至上颜色渐变…
[android:startColor] 渐变开始的颜色

[android:endColor] 渐变结束时的颜色

[android:centerColor] 渐变中间的颜色(可有可无)

如果要将圆角和渐变结合起来,只要将<solidandroid:color>替换成<gradient...>就行了

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:topLeftRadius="20dp"
        android:topRightRadius="20dp"
        android:bottomRightRadius="20dp"
        android:bottomLeftRadius="20dp"/>
    <stroke android:width="1dp" android:color="@color/black" />
    <gradient
        android:angle="180"
        android:endColor="@color/colorPrimary"
        android:centerColor="@color/blue"
        android:startColor="@color/colorAccent" />
</shape>

如图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值