Android的 - 如何通过编程定义ShapeDrawables? [英] Android - how to define ShapeDrawables programmatically?

查看:102
本文介绍了Android的 - 如何通过编程定义ShapeDrawables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现是使用可绘制与一对夫妇里面层,但在运行时控制一些值,如startColor渐变。下面是我在my_layered_shape.xml:

What I'm trying to achieve is to use a Drawable with a couple of layers inside it, but control some values at runtime such as the startColor for the gradient. Here's what I have in my_layered_shape.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  <item>
    <shape android:shape="rectangle">
      <stroke android:width="1dp" android:color="#FF000000" />
      <solid android:color="#FFFFFFFF" />
    </shape>
  </item>
  <item android:top="1dp" android:bottom="1dp"> 
    <shape android:shape="rectangle">
    <stroke android:width="1dp" android:color="#FF000000" />
    <gradient
      android:startColor="#FFFFFFFF"
      android:centerColor="#FFFFFF88"
      android:endColor="#FFFFFFFF"
      android:gradientRadius="250"
      android:centerX="1"
      android:centerY="0"
      android:angle="315"
    />            
    </shape>
  </item>
</layer-list>

如果我用mMyImageView.setBackgroundResource(R.drawable.my_layered_shape)它的工作原理。 我不介意分裂的XML,如果我必须这样做,或做整个事情编程,只要有一种方式来获得的各种颜色值。我要以编程方式(即我最好的射击在做在code,因为这XML相同)的概念是:

And if I use mMyImageView.setBackgroundResource(R.drawable.my_layered_shape) it works. I don't mind splitting the xml if I have to, or doing the whole thing programatically as long as there's a way to get at the various color values. The concept I'm going for programmatically (i.e. my best shot at doing the same in code as this xml) is:

Drawable[] layers = new Drawable[2];

ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
sd1.getPaint().setColor(0xFFFFFFFF);
sd1.getPaint().setStyle(Style.STROKE);
sd1.getPaint().setStrokeWidth(1);
// sd1.getPaint().somehow_set_stroke_color?

ShapeDrawable sd2 = new ShapeDrawable(new RectShape());
sd2.getPaint().setColor(0xFF000000);
sd2.getPaint().setStyle(Style.STROKE);
// sd2.getPaint().somehow_set_stroke_color?
// sd2.getPaint().somehow_set_gradient_params?

layers[0] = sd1;
layers[1] = sd2;
LayerDrawable composite = new LayerDrawable(layers);
mMyImageView.setBackgroundDrawable(composite);

感谢。

推荐答案

这似乎是不符合的 ShapeDrawable 的工作,但看看我的 GradientDrawable 的例子:

It seems that is does not work with ShapeDrawable, but take a look at my GradientDrawable example:

GradientDrawable gd = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]{Color.RED, Color.GREEN});
gd.setStroke(10, Color.BLUE);

您可能还需要下面的方法:

You may also need following method:

gd.setGradientCenter(float x, float y);
gd.setGradientRadius(float gradientRadius);

这篇关于Android的 - 如何通过编程定义ShapeDrawables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆