gpt4 book ai didi

java - 如何以编程方式为 View 创建渐变颜色背景?

转载 作者:行者123 更新时间:2023-12-02 10:24:09 25 4
gpt4 key购买 nike

strong text有一个界面组件View(简单的矩形),我们称之为“my_view”。...

View myView = (View) findViewById(R.id.my_view);

...我想以编程方式为 myView 创建线性渐变颜色背景。渐变的两种颜色由经常变化的变量设置。所以我需要找到一种优化的方法。我尝试这样做:

myView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
@Override
public boolean onPreDraw()
{
myView.getViewTreeObserver().removeOnPreDrawListener(this);
int view_height = myView.getHeight();
ShapeDrawable myDrawable = new ShapeDrawable(new RectShape());
myDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, view_height, color1, color2, Shader.TileMode.CLAMP));
myView.setBackgroundDrawable(myDrawable);
return false;
}
});

一切正常。每次当 Seekbar 的进度发生变化时,都应该执行此代码。经过测试,我意识到这是一个非常糟糕的方法。一切正常,但滞后很明显。

<小时/>

更新:问题解决了!最好的方法是创建自定义绘图!感谢所有给我建议的论坛成员,特别是pskink,他给了我最好的建议。

最佳答案

使用可以动态选择颜色并这样使用。

    int[] colors = {Color.parseColor("#008000"),Color.parseColor("#ADFF2F")};

//create a new gradient color
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, colors);

gd.setCornerRadius(0f);
//apply the button background to newly created drawable gradient
view.setBackground(gd);

关于java - 如何以编程方式为 View 创建渐变颜色背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54105494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com