如何在android中使用ShapeDrawable以编程方式创建圆角边框?

use*_*512 16 java android border drawable shapedrawable

我需要通过扩展ShapeDrawable以编程方式创建带圆角的边框.我需要一个带圆角的黑色边框,外面的像素是白色,内部像素是透明的.我目前的代码存在多个问题,其中的问题是它不会创建一个与边框厚度相同的平滑角,并且边框的外部像素是透明的而不是白色.

这是我目前得到的角落的图片 角

这是我在构造函数中为'fill'传递Color.TRANSPARENT的代码:

public class CustomShape extends ShapeDrawable {
 private final Paint fillpaint, strokepaint;
public CustomShape(int fill, int strokeWidth,int radius) {

    super(new RoundRectShape(new float[] { radius, radius, radius, radius, radius, radius, radius, radius }, null, null));
    fillpaint = new Paint(this.getPaint());
    fillpaint.setColor(fill);
    strokepaint = new Paint(fillpaint);
    strokepaint.setStyle(Paint.Style.STROKE);
    strokepaint.setStrokeWidth(strokeWidth);
    strokepaint.setColor(Color.BLACK);
}



@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
    shape.draw(canvas, fillpaint);
    shape.draw(canvas, strokepaint);
}
Run Code Online (Sandbox Code Playgroud)

}

SGa*_*Gal 21

如果你需要均匀的圆角(并且从你的例子中看起来像你那样),你可以简单地使用纯色的GradentDrawable

GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.RED);
gd.setCornerRadius(10);
gd.setStroke(2, Color.WHITE);

view.setBackground(gd);
Run Code Online (Sandbox Code Playgroud)

可在此处找到GradientDrawable文档.

编辑:分别为每个角落

您可以使用setCornerRadii (float[] radii)方法分别指定每个角的半径."对于每个角,数组包含2个值,[X_radius,Y_radius].角是按左上,右上,右下,左下排序的.仅当形状为RECTANGLE类型时,才会使用此属性.

建议mutate()在更改此属性之前调用.


mun*_*ikh 0

您可以实现自定义绘图。以下是 xml 的示例。

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    

    <stroke android:width="3dp"
            android:color="#ff000000"
            />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp"
             /> 

    <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" 
     android:topLeftRadius="7dp" android:topRightRadius="7dp"/> 
</shape>
Run Code Online (Sandbox Code Playgroud)

将此 xml 保存在项目的可绘制文件夹中。现在将它像任何小部件的普通可绘制对象一样使用。例如: android:background="R.drawable.round_shape"

此示例在以下链接中引用。