Android: Change center of linear GradientDrawable via code

烂漫一生 提交于 2019-11-28 08:57:32

问题


EDIT: LOOK AT SOLUTION ABOVE

i m freaking out. all i just want to do, is setting a linear GradientDrawable, which changes the vertical center of the gradient... drawing the gradient works fine, but how can i change the center of it?!?

RelativeLayout bgScreen = (RelativeLayout) findViewById(R.id.player_screen);

GradientDrawable gd = new GradientDrawable(
     GradientDrawable.Orientation.TOP_BOTTOM,
     new int[] {startColor,endColor});

gd.setCornerRadius(0f);
gd.setAlpha(200);
bgScreen.setBackground(gd); 


public void redrawOrChangeBackgroundGradient(){
    //??? either change center of existing
    gd.setGradientCenter(float x, float y) //ONLY works in RADIAL_GRADIENT or SWEEP_GRADIENT.

    //??? or complete redraw Gradient with different center

}

here s a picture example of how i want to change the gradient via code

cannot be that hard, can it?


回答1:


The lacking ability to set the center programmatically for linear GradientDrawables is a registered issue already.

But there is a workaround described here. Basically, you should create a PaintDrawable from a LinearGradient and set it as your view's background drawable. Following this solution, you can set the center in your LinearGradient constructor by mapping the colors to the positions array:

float[] positions

May be null. The relative positions [0..1] of each corresponding color in the colors array. If this is null, the colors are distributed evenly along the gradient line.

(not tested, but it should do the trick for you)



来源:https://stackoverflow.com/questions/14382872/android-change-center-of-linear-gradientdrawable-via-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!