在Android的可绘制对象中,是否可以将圆角半径指定为百分比?

9
作为Android可绘制对象,它代表一个带有圆角的黑色矩形。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="20dp" />
    <solid android:color="#000000" />
</shape>

然而,角落的半径被指定为绝对值20dp,因此如果在不同的大小下显示相同的可绘制对象,则会出现不同的外观。 较小的形状不仅仅是较大形状的“缩小”版本。 相反,它更加“圆润”,而较大的形状则更加“方形”,因为边框半径是静态的20dp,无论可绘制对象的大小如何。

absolute border radius

我希望能够相对于完整绘制对象的大小指定半径,这样当以不同的大小绘制时,每个绘制对象都会呈现为缩放的放大/缩小版本。

relative border radius

我更熟悉CSS,在那里这可以用一行代码实现:

border-radius: 20%;

我很惊讶地发现Android缺乏这种CSS的简洁性。Android不认识%作为一种单位。

<corners android:radius="20%" />

有没有一种简单的方法在Android中实现我的期望结果?

android: radius expects a dimension so I don't think you can specify in % not alteast in XML - Sekiro
你有没有找到解决办法? - adrem7
1个回答

2

你是对的,这方面没有内置的方法。但是你可以通过编程实现它。我以前写过这个小类,对我有用。

    public class CornerDrawable extends GradientDrawable {

    private float percent;

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        super.setBounds(left, top, right, bottom);
        setCornerRadius(getBounds().height() / percent);
    }

    @Override
    public void setBounds(@NonNull Rect bounds) {
        super.setBounds(bounds);
        setCornerRadius(getBounds().height() / percent);
    }

    /**
     * Sets the corner radius of each corner to the <code>percent</code> of the height of this drawable. For example, passing
     * <i>50</i> will result in a fully rounded side of the target view.
     *
     * @param percent The percentage of the height of the view to be rounded
     */
    public void setCornerRadiusPercent(float percent) {
        this.percent = 100 / percent;
    }
}

接着,您只需要创建一个实例并按照您的要求进行配置,并将其设置在目标视图上。例如像这样:

    //the view you want to apply the corner radius to
    View targetView = ...
    CornerDrawable cornerDrawable = new CornerDrawable();
    //pass your desired percent value
    cornerDrawable.setCornerRadiusPercent(20);
    // set the solid color from your xml above
    cornerDrawable.setColor(getResources().getColor(R.color.black, requireContext().getTheme()));
    targetView.setBackground(cornerDrawable);

这样做的唯一缺点是,你必须通过编程来完成所有配置,而不能使用你的可绘制的xml文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接