我已经为矩形形状创建了一个类,因为它是我的应用程序中的一个对象。但现在我希望角落是圆角的。在下面您可以看到它是一个简单的类,用于创建我想要的具有相同属性的尽可能多的矩形。
public class customDrawable extends ShapeDrawable {
public void setCustomDrawableAttributes(ShapeDrawable shapeDrawable){
int x = 0;
int y = 0;
int width = 100;
int height = 100;
shapeDrawable.setBounds(x, y-height, x + width,y+height );
}
public ShapeDrawable createShape(){
return new ShapeDrawable(new RectShape());
}
}
更新:如果没有这个方法,我将不会绘制任何内容,因为没有尺寸。用它它只绘制通常的矩形。 (整数值已更改为不显示应用程序特定方法)
public void setDrawableAttributes(ShapeDrawable shapeDrawable){
int x = 0;
int y = 500
int width = 200
int height = 300
shapeDrawable.setBounds(x, y-height, x + width,y+height );
}
根据我的研究,我发现我不能简单地添加圆角,而是必须创建一个 RoundRectShape shapeDrawable
。我使用此 RoundRectShape
创建圆角矩形的每次尝试都失败了。不知何故,形状最终总是成为一个没有圆角的规则矩形。
我正在寻找一个简单的类(如提供的类)来创建一个 roundRectShape 可绘制对象。只要具有圆角,高度和宽度并不重要。必须是 Java 格式,而不是 XML 格式。
我尝试创建圆角矩形的链接:
1. https://developer.android.com/reference/android/graphics/drawable/shapes/RoundRectShape.html
6. Android: RoundRectShape: Modify corner radii
8. http://www.edumobile.org/android/shape-drawing-example-in-android/ 9.http://programtalk.com/java-api-usage-examples/android.graphics.drawable.shapes.RoundRectShape/
最佳答案
我创建了一个类MyRect
,用于为您绘制圆角矩形。
public class MyRect {
public static Paint paint; // default paint use for all my MyRect objects
static {
paint=new Paint();
paint.setColor(Color.RED);
}
public float x,y,width,height;
public float roundStrength=30;
public MyRect(float x, float y, float width,float height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
public MyRect(float x, float y, float width,float height,float roundStrength){
this(x,y,width,height);
this.roundStrength=roundStrength;
}
public void draw(Canvas canvas){
canvas.drawRoundRect(x-width/2,y-height/2,x+width/2,y+height/2,roundStrength,roundStrength,paint);
}
}
创建上面的MyRect
对象是不够的,我们需要在任何容器中保留对象的引用,以便我们将来可以修改或删除该对象。
static ArrayList<MyRect> myRects=new ArrayList<>();
在View
/SurfaceView
的onDraw(Canvas canvas)
方法内部调用MyRect的draw()
方法。
for(MyRect rect:myRects)
rect.draw(canvas);
完成,创建对象并添加到容器。
myRects.add(new MyRect(touchx,touchy,100,100));
或
myRects.add(new MyRect(touchx,touchy,100,100,50));
您还可以根据您的要求扩展MyRect
,例如添加更多构造函数、方法和数据成员。
关于java - Android Canvas : Create RoundRectShape Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960477/