2014-01-28 39 views
9

我想要对线性渐变的中心进行动画处理,以便在整个绘图开始时整个绘图为color1,最后整个绘图为color2,渐变的中心从左向右移动。LinearGradient中心动画

GradientDrawable gd = new GradientDrawable(
           GradientDrawable.Orientation.LEFT_RIGHT, 
           new int[] {color1, color2}); 
gd.setCornerRadius(0f); 
gd.setGradientCenter(x, 0); 
view.setBackgroundDrawable(gd); 

问题是setGradientCenter没有任何区别。根据这个回答https://stackoverflow.com/a/14383974/1395697 setGradientCenter()有一个问题,但是这个答案中的解决方案对我来说不起作用,因为当用户在视图上滑动他的手指时,我改变了onTouch()中的渐变,所以它需要是真正的快速。

有没有办法做到这一点?

我想要做这样的事情(所有的触摸东西的伟大工程,但没有动画渐变):

enter image description here

+0

像cyanogenmod锁屏动画http://svij.org/graphics/android-lockscreen_cyanogenmod.png?请不要在Android问题的标题前加上前缀,底部的标签就足够了。 – Luksprog

+0

我添加了一个截图来展示我的意思。 – DominicM

回答

3

什么你问的是不是一个纯粹的线性渐变 - 之间的线性渐变固定宽度上的两种颜色只有一种数学函数定义它,这就是为什么你不能改变中心。 我认为你正在寻找的是一个固定的颜色开始和结束,以及它们之间的线性渐变区域。

尝试这种解决方案:

sf = new ShapeDrawable.ShaderFactory() { 
    @Override 
    public Shader resize(int width, int height) { 
     LinearGradient lg = new LinearGradient(0, 0, view.getWidth(), 0, new int[] {Color.WHITE, Color.BLACK}, //substitute the correct colors for these 
       new float[] {center - 0.3f, center + 0.3f}, Shader.TileMode.REPEAT); 
     return lg; 
    } 
    }; 
    p = new PaintDrawable(); 
    rectShape = new RectShape(); 
    p.setShape(rectShape); 
    p.setShaderFactory(sf); 
    view.setBackgroundDrawable((Drawable) p); 
    view.setOnTouchListener(new View.OnTouchListener() { 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     center = event.getX()/view.getWidth(); // calculate the center 
     p.setShape(rectShape); // this makes the shader recreate the lineargradient 
     return true; 
    } 
    }); 

此代码似乎不够快,触摸反应,但会创建的LinearGradient的多个实例。

0

你可以用seekbar做这样的事情。

你将需要设置一个自定义的progressDrawable属性,并删除位置标记(拇指)这样的事情。

<SeekBar 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:progressDrawable="@drawable/gradient_progress" 
    android:thumb="@null"/> 

gradient_progress.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:id="@android:id/background" 
      android:drawable="@drawable/right_colour" /> 
    <item android:id="@android:id/secondaryProgress"> 
     <scale android:scaleWidth="100%" 
       android:drawable="@drawable/left_colour" /> 
    </item> 
    <item android:id="@android:id/progress"> 
     <scale android:scaleWidth="100%" 
       android:drawable="@drawable/left_colour" /> 
    </item> 
</layer-list> 

其中right_colour是右手的颜色(蓝色)和left_colour的可拉伸或颜色资源是左手颜色的9-补丁可绘制(绿色)渐变为透明,只会拉伸最左边缘。我的是这样

left_colour.9.png(它是白色的渐变为透明的,所以很难看到这里)

这给出了一个解决方案,快速,不需要您的任何触摸编码,但它确实有一个缺点,它不太适合远端,所以即使用户一直移动,图像的“线性渐变”部分仍然可见。如果这不是一个大问题,那么这将工作得很好。