Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radial Gradient for different dpi

I'm creating a radial gradient like:

 <?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>

But in the gradientRadius field using values like sp and dip return an error. Is there a way to specify the radius and scale for mdpi and scale it automatically in the rest of screen densities, or is necessary to create multiple drawable files?

like image 799
Addev Avatar asked Dec 14 '11 08:12

Addev


2 Answers

Old question, but this answer shows highly ranked in Google and I belief an alternative approach is more scaleable. Instead of having to supply the dimension for every density, create a density-independent dimension from XML:

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

Since we cannot apply this directly to the radial gradient XML drawable, we have to apply in from code:

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

This overrides the android:gradientRadius field, so you can leave that to 0. You can still not use a (screen based or otherwise) % dimension, though. I apply this to the background of my view (to which the gradient drawable is already set!) but it applies to an ImageView's src element as well, of course.

like image 31
Eric Kok Avatar answered Oct 04 '22 04:10

Eric Kok


So what if you do this:

res/drawable/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/values-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>

What do you think?

like image 169
Greg Giacovelli Avatar answered Oct 04 '22 04:10

Greg Giacovelli