7

以下のような 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);

GradientDrawableしかし、Stroke(?) を作成してから Stroke とtoの両方を割り当てる方法がわかりませんShape

何か案が?

4

3 に答える 3

8

例:

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);
    }


}

結果:

描画可能な結果画像

于 2013-07-20T08:29:54.547 に答える
0

これはきっとうまくいくはずです、試してみてください 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,centerは内部で次のように定義されてcolors.xml います。

 <color name="stroke">#FF333333</color>
 <color name="start">#333</color> 
 <color name="center">#ddd</color>
于 2013-07-20T08:02:06.120 に答える
-5

コードで作成する場合は、最初に res.getDrawable(resId) によって返されるクラス インスタンスを調べます。

Drawable d = res.getDrawable(R.drawable.shape)
Log.d(TAG, "d: " + d)
于 2013-07-20T07:22:02.227 に答える