L1g*_*ira 0 java android android-canvas shapedrawable android-shapedrawable
我为矩形创建了一个类,因为它是我的应用程序中的一个对象。但是现在我希望角落是圆的。在下面你可以看到它是一个简单的骨骼类,用于创建我想要的具有相同属性的任意数量的矩形。
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());
}
}
Run Code Online (Sandbox Code Playgroud)
更新:如果没有这种方法,我将无法绘制任何内容,因为没有大小。有了它,它只绘制通常的矩形。(更改为不显示特定于应用程序的方法的整数值)
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 );
Run Code Online (Sandbox Code Playgroud)
}
从我的研究中,我发现我不能简单地添加圆角,而是必须创建一个RoundRectShape shapeDrawable. 我使用此方法创建带圆角的矩形的每次尝试都RoundRectShape失败了。不知何故,形状总是最终成为一个没有圆角的规则矩形。
我正在寻找一个简单的骨骼类(就像提供的那个),它创建一个 roundRectShape 可绘制对象。只要有圆角,高度和宽度无关紧要。必须是 Java 而不是 XML。
我尝试创建圆角矩形的链接:
1. https://developer.android.com/reference/android/graphics/drawable/shapes/RoundRectShape.html
6、Android:RoundRectShape:修改圆角半径
8. http://www.edumobile.org/android/shape-drawing-example-in-android/ 9. http://programtalk.com/java-api-usage-examples/android.graphics.drawable.shapes。圆角矩形/
我创建了一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
创建上面的对象MyRect是不够的,我们需要在任何容器中保留对象的引用,以便我们将来可以修改或删除该对象。
static ArrayList<MyRect> myRects=new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
里面onDraw(Canvas canvas)的方法View/SurfaceView调用MyRect的draw()方法。
for(MyRect rect:myRects)
rect.draw(canvas);
Run Code Online (Sandbox Code Playgroud)
完成,创建对象并添加到容器。
myRects.add(new MyRect(touchx,touchy,100,100));
Run Code Online (Sandbox Code Playgroud)
或者
myRects.add(new MyRect(touchx,touchy,100,100,50));
Run Code Online (Sandbox Code Playgroud)
您还可以MyRect根据需要进行扩展,例如添加更多构造函数、方法和数据成员。
| 归档时间: |
|
| 查看次数: |
3329 次 |
| 最近记录: |