【问题标题】:LinearGradient Center Animation线性渐变中心动画
【发布时间】:2014-01-28 10:32:15
【问题描述】:
我想为线性渐变的中心设置动画,这样一开始整个drawable是color1,最后整个drawable是color2,渐变中心从左到右移动。
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT,
new int[] {color1, color2});
gd.setCornerRadius(0f);
gd.setGradientCenter(x, 0);
view.setBackgroundDrawable(gd);
问题在于 setGradientCenter 没有任何区别。根据这个答案https://*.com/a/14383974/1395697 setGradientCenter() 有一个问题,但是这个答案中的解决方案对我不起作用,因为当用户在视图上滑动手指时我改变了 onTouch() 中的渐变,所以它需要非常快。
有没有办法做到这一点?
我想做这样的事情(所有的触摸效果都很好,但动画渐变效果不行):
【问题讨论】:
标签:
android
animation
gradient
linear-gradients
【解决方案1】:
您要求的不是纯线性渐变 - 固定宽度上两种颜色之间的线性渐变只有一个定义它的数学函数,这就是您无法更改中心的原因。
我认为您正在寻找的是一个固定的颜色开始和结束,以及它们之间的线性渐变区域。
试试这个解决方案:
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 实例。
【解决方案2】:
你可以用搜索栏做这样的事情。
您将需要设置一个自定义的 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-patch 可绘制资源,只会拉伸最左边的边缘。我的是这样的
(这里是白色渐变到透明很难看到)
这提供了一个快速的解决方案,并且不需要您进行任何触摸编码,但它确实有一个缺点,它不能完全到达远端,因此图像的“线性渐变”部分是即使用户已经完全移动,仍然可见。如果这不是一个大问题,那么这会很好。