开发者

Vertical-striped background in XML?

I want to set a View background that is a regular grid of vertical stripes. The stripes alternate between two colors. (For example, across a single row, there might be 6 pixels of light gray followed by 2 pixels of dark gray, repeated to fill the width.)

It's easy enough to do this using a Bitmap (either as a resource or generated in code). For instance:

ShapeDrawable bg = new ShapeDrawable(new RectShape());
int[] pixels = new int[] { 0xFFCCCCCC, 0xFFCCCCCC, 0xFFCCCCCC,
    0xFFCCCCCC开发者_JAVA百科, 0xFFCCCCCC, 0xFFCCCCCC, 0xFF999999, 0xFF999999};
Bitmap bm = Bitmap.createBitmap(pixels, 8, 1, Bitmap.Config.ARGB_8888);
Shader shader = new BitmapShader(bm,
    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
bg.getPaint().setShader(shader);
view.setBackgroundDrawable(bg);

Is there a way to do this strictly as XML drawables, without using bitmap resources?


Unfortunate, but I'm pretty sure the answer is no.

Of the three tasks required, only two could be done without any code. You can create the base of the stripes pattern as a <layer-list> of two or more <shape> items. You can also create a repeating tile pattern using a <bitmap> XML drawable. The trick is the required middle step: <bitmap> will not accept another drawable as a source value (only an image) so there is no way to link the two without the intervention of a little code to create a Bitmap (like what you have written).

I would love to see tile modes applied to more drawables as well, and +1 for giving me a sample of creating the pattern completely in code :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜