2011-12-14 30 views
16

我创建一个径向渐变,如:径向渐变为不同的DPI

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
<gradient 
     android:startColor="#7faacaFF" 
     android:endColor="#cfe1edFF" 
     android:gradientRadius="326" 
     android:type="radial"/> 
</shape> 

但在使用像SP和倾角值gradientRadius场返回一个错误。 有没有一种方法可以指定mdpi的半径和缩放比例,并在余下的屏幕密度中自动缩放或者创建多个可绘制文件?

回答

22

那么,如果你这样做:

RES /绘制/ foo.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
           android:shape="rectangle"> 
<gradient 
     android:startColor="#7faacaFF" 
     android:endColor="#cfe1edFF" 
     android:gradientRadius="@dimen/radius" 
     android:type="radial"/> 
</shape> 

RES /价值观MDPI/dimens.xml

<resources ...> 
... 
<item name="radius" format="float" type="dimen">326</item> 
.... 

</resources> 

res/values-hdpi/dimens.xml

<resources ...> 
... 
<item name="radius" format="float" type="dimen">200.34</item> 
.... 

</resources> 

您怎么看?

+0

非常感谢,这应该被接受为回应 – Arnaud 2014-08-25 09:42:35

0

docs表示您可以将gradientRadius属性指定为float(猜测它意味着px)或分数。

可能是一个小数值,它是一个浮点数,后面跟着%或%p,例如“14.5%”。 %后缀始终表示基本大小的百分比;可选的%p后缀提供了相对于某个父容器的大小。

你试过吗?这样可以用dp或布局中的任何单位指定大小,并从这里引用它。但奇怪的是,大多数尺寸被指定为可绘制xml格式的尺寸。

+4

那么,我试着用自己的方式,并不能得到它的工作。这似乎是刚分出的百分比,因此上面提到的基本大小是1px。 %p表示法也一样,所以这是一个失败...我的坏:| – 2012-09-07 09:44:41

+0

分数不适用于Kitkat(API 19)和更低,也不是50%不是50%p,可绘制只是没有显示 – 2016-07-05 10:42:37

-2

在android:gradientRadius字段中使用百分比。

例子:

对于50%radious设置为50000%P

<gradient 
       android:angle="45" 
       android:centerX="0.5" 
       android:centerY="0.5" 
       android:endColor="#123123" 
       android:gradientRadius="50000%p" 
       android:startColor="#456456" 
       android:type="radial" /> 
8

老问题,但这个答案显示了高排名在谷歌和我的信仰的替代方法更可扩展性。而不必提供尺寸为每密度,从XML创建密度无关尺寸:

<dimen name="gradient_radius">25dp</dimen> 

因为我们不能直接应用此径向渐变XML绘制的,我们必须从代码到应用:

((GradientDrawable) someView.getBackground()) 
     .setGradientRadius(getResources().getDimension(
      R.dimen.yellowbadge_largeradius)); 

这覆盖了android:gradientRadius字段,因此您可以将其保留为0.但是,仍然不能使用(基于屏幕或其他方式)百分比维度。我将它应用于我的视图的背景(已经设置了渐变drawable),但它当然也适用于ImageView的src元素。