【问题标题】:Create a Shape dynamically动态创建形状
【发布时间】:2013-07-20 16:29:54
【问题描述】:

我有一个用 XML 定义的形状对象,如下所示:

<shape android:shape="rectangle">
    <gradient
        android:startColor="#333"
        android:centerColor="#DDD"
        android:endColor="#333"/>
    <stroke android:width="1dp" android:color="#FF333333" />
</shape>

我想在我的代码中创建一个相等的对象。 我创建了一个GradientDrawable 如下:

gradientDrawable1.setColors(new int[] { 0x333, 0xDDD, 0x333 });
gradientDrawable1.setOrientation(Orientation.TOP_BOTTOM);

但我不知道如何创建一个 Stroke(?) 然后将 Stroke 和 GradientDrawable 分配给 Shape

有什么想法吗?

【问题讨论】:

    标签: android android-drawable


    【解决方案1】:

    例子:

    import android.graphics.drawable.GradientDrawable;
    
    public class SomeDrawable extends GradientDrawable {
    
        public SomeDrawable(int pStartColor, int pCenterColor, int pEndColor, int pStrokeWidth, int pStrokeColor, float cornerRadius) {
            super(Orientation.BOTTOM_TOP,new int[]{pStartColor,pCenterColor,pEndColor});
            setStroke(pStrokeWidth,pStrokeColor);
            setShape(GradientDrawable.RECTANGLE);
            setCornerRadius(cornerRadius);
        }
    
    }
    

    用法:

    public class MyActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            SomeDrawable vDrawable = new SomeDrawable(Color.BLACK,Color.GREEN,Color.LTGRAY,2,Color.RED,50);
            View vView = new View(this);
            vView.setBackgroundDrawable(vDrawable);
            setContentView(vView);
        }
    
    
    }
    

    结果:

    【讨论】:

      【解决方案2】:

      这应该肯定有效试试gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));

      所以你的代码应该是

          GradientDrawable gradientDrawable1 = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{getResources().getColor(R.color.start),getResources().getColor(R.color.center),getResources().getColor(R.color.start)} );
          gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));
      

      其中 color stroke,start,centercolors.xml 中定义 as:

       <color name="stroke">#FF333333</color>
       <color name="start">#333</color> 
       <color name="center">#ddd</color>
      

      【讨论】:

        【解决方案3】:

        如果你想在代码中创建它,首先检查 res.getDrawable(resId) 返回的类实例,例如:

        Drawable d = res.getDrawable(R.drawable.shape)
        Log.d(TAG, "d: " + d)
        

        【讨论】:

        • 我不想从资源中获取对象。我想在java代码中动态创建它。
        • 你做了我写的吗?输出是什么?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 2016-06-18
        • 2012-07-01
        • 1970-01-01
        • 2019-05-27
        • 1970-01-01
        相关资源
        最近更新 更多