问题描述
我需要通过扩展ShapeDrawable以编程方式创建带圆角的边框。我需要一个带圆角的黑色边框,外面的像素是白色,内部像素是透明的。我目前的代码有很多问题,其中的问题是它不会创建一个与边框厚度相同的光滑角落,并且边框的外部像素是透明的而不是白色。
I need to create a border with rounded corners programatically by extending ShapeDrawable. I need to have a black border with rounded corners with the pixels on the outside being white and the inner pixels being transparent. The code I have at the moment has multiple problems, of which are that it does not create a smooth corner that is the same thickness as the border and that the outer pixels of the border are transparent and not white.
这是我目前正在拍摄的角落的照片
Here is a picture of the corners I am currently getting
以下是我在构造函数中为'fill'传递Color.TRANSPARENT的代码:
Here is the code where I am passing Color.TRANSPARENT for 'fill' in the constructor:
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);
}
}
推荐答案
如果你需要均匀圆角(并且从你的例子中看起来像你那么做)你可以简单地使用纯色的GradentDrawable
If you need evenly rounded corners (and from your example it seems you do) you can simply use GradentDrawable with a solid color
GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.RED);
gd.setCornerRadius(10);
gd.setStroke(2, Color.WHITE);
view.setBackground(gd);
可以找到GradientDrawable文档。
GradientDrawable documentation can be found here.
编辑:分别为每个角落
您可以使用 setCornerRadii(float [] radiusii)
方法分别指定每个角的半径。 对于每个角,数组包含2个值,[X_radius,Y_radius]。角是按左上,右上,右下,左下排序的。仅当形状为RECTANGLE类型时才会使用此属性。
You can specify radius of each corner separately using setCornerRadii (float[] radii)
method. "For each corner, the array contains 2 values, [X_radius, Y_radius]. The corners are ordered top-left, top-right, bottom-right, bottom-left. This property is honored only when the shape is of type RECTANGLE.
建议在更改此属性之前调用 mutate()
。
It is recommended to invoke mutate()
before changing this property.
这篇关于如何在android中使用ShapeDrawable以编程方式创建一个圆形的角落边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!