在这里提到我的第一个问题(Android: Change center of linear GradientDrawable via code),我仍在努力尝试改变背景的渐变中心。
基本上,我想根据系统音量改变背景中线性渐变的中心。因此,如果用户更改音量,则渐变是(#1)重绘或(#2)更改位置:
#1:有一个Shader Factory的线性渐变的解决方法
ShapeDrawable.ShaderFactory sf=new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, 0, width, height,
new int[]{Color.WHITE, Color.GRAY, Color.BLACK},
new float[]{0,0.5f,1}, Shader.TileMode.MIRROR);
}
};
但是这个解决方案的问题是,有几种不同的梯度模式,背景会被改变,并且每次重新绘制卷都会改变...因为它是一个流应用程序,我不确定这种情况下的性能
所以我来到解决方案#2。如果选择了每个线性渐变,我会绘制一次,并在例如大于设备屏幕的视图中绘制它。
现在,如果用户打开音量,屏幕就会在Y轴上移动。但是,我尝试使用线性渐变和Shader Factory,但每次背景视图渐变都与屏幕设备一样大而不是更大。
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y + 500; //change height to higher than parentview
//get a background and change layout (tried with view,relativelayout as well)
LinearLayout backgroundGradientView = (LinearLayout)
findViewById(R.id.player_backgroundGradient);
backgroundGradientView.getLayoutParams().width = width;
backgroundGradientView.getLayoutParams().height = height;
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, new int[] { startColor, endColor });
backgroundGradientView.setBackground(gd);
//later, i m changing the Y Value, but the background is as big as the parent
backgroundGradientView.setY(currentY + 100)
任何人都有任何想法如何改变这个?我真的不知道如何解决这个案子?!
答案 0 :(得分:0)
好的,搞定了。我终于使用了Shader Factory解决方案。不知道每次重绘渐变的性能是否最好,但至少它是有效的。所以这里是根据android设备音量改变背景渐变:
//global variables, because they can change during runtime
private int startColor;
private int endColor;
private float gradientCenter;
// call this, after every volume change, gradientCenter is a value between 0.0-0.5f, depending on the current volume
//...
AudioManager audMgr = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audMgr.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
gradientCenter = 0.5f - (float) currentVolume / (float) maxVolume
* 0.5f;
drawBackground();
//...
private void drawBackground() {
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
(YOUR_VIEW_FOR_BACKGROUND).setBackgroundDrawable(p);
}
//ShaderFactory is using the global gradientCenter,startColor and endColor
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, 0, 0, height, new int[] { startColor,
endColor }, new float[] { gradientCenter, 1.0f },
Shader.TileMode.CLAMP);
}
//...