Android:如何在代码中创建此资源形状?

时间:2011-12-23 11:01:03

标签: android

我在xml文件中定义了这个形状,需要在代码中创建它,但是我很难过。

我假设我想实例化RoundRectShape并将其属性设置为xml中的属性,但属性不能很好地排列。

RoundRectShape(float[] outerRadii, RectF inset, float[] innerRadii)

我的xml形状只有1个半径,现在是RectF,而RoundRectShape没有设置填充或颜色的选项?

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#00FFFFFF" />
    <stroke android:width="2dp" android:color="#FFFFFFFF" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="7dp" /> 
    <corners android:radius="4dp" /> 
</shape> 

1 个答案:

答案 0 :(得分:2)

您需要创建自定义可绘制的内容,如下所示

示例代码

public class CustomDrawable extends ShapeDrawable{
    Paint fillpaint, strokepaint;
    private static final int WIDTH = 2; 

@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
    // TODO Auto-generated method stub
//  super.onDraw(shape, canvas, paint);
    fillpaint = this.getPaint();
    strokepaint = new Paint(fillpaint);
    strokepaint.setStyle(Paint.Style.STROKE);
    //to set stroke width and color instead of <stroke android:width="2dp" android:color="#FFFFFFFF" /> 
    strokepaint.setStrokeWidth(WIDTH);
    strokepaint.setARGB(255, 255, 255, 255);

    shape.draw(canvas, fillpaint);
    shape.draw(canvas, strokepaint);

}
}