java 如何在 SeekBar 中制作颜色渐变?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4342757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a color gradient in a SeekBar?
提问by JPM
I want to use a SeekBar (i.e. old school Java Slider) into a color gradient picker. I have seen some examples like this but they all require making new classes and such. There has got to be a way to modify or override the original classes. Or just replace the background with a gradient.
我想在颜色渐变选择器中使用 SeekBar(即老式 Java Slider)。我见过一些这样的例子,但它们都需要创建新的类等等。必须有一种方法来修改或覆盖原始类。或者只是用渐变替换背景。
回答by JPM
I figured it out here is how you do it.
我想出这就是你如何做到的。
You create a standard seekbar in your XML.
您在 XML 中创建了一个标准的搜索栏。
<SeekBar
android:id="@+id/seekbar_font"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:layout_below="@id/color_font_text"
android:max="100"
android:progress="50"></SeekBar>
Then you customize the seekbar in your onCreate() by creating a boxShape and then force a LinearGradient inside it.
然后通过创建一个 boxShape 并在其中强制使用 LinearGradient 来自定义 onCreate() 中的搜索栏。
LinearGradient test = new LinearGradient(0.f, 0.f, 300.f, 0.0f,
new int[] { 0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF,
0xFFFF0000, 0xFFFF00FF, 0xFFFFFF00, 0xFFFFFFFF},
null, TileMode.CLAMP);
ShapeDrawable shape = new ShapeDrawable(new RectShape());
shape.getPaint().setShader(test);
SeekBar seekBarFont = (SeekBar)findViewById(R.id.seekbar_font);
seekBarFont.setProgressDrawable( (Drawable)shape );
Here is an image of the current code up above SeekBar Color Gradient
这是当前代码在SeekBar Color Gradient上方的图像
回答by Avinash
This is in addition to the solution provided using LinearGradient. Try this logic for translating the progress to rgb:
这是使用 LinearGradient 提供的解决方案的补充。试试这个将进度转换为 rgb 的逻辑:
lineColorSeekbar.setMax(256*7-1);
lineColorSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
int r = 0;
int g = 0;
int b = 0;
if(progress < 256){
b = progress;
} else if(progress < 256*2) {
g = progress%256;
b = 256 - progress%256;
} else if(progress < 256*3) {
g = 255;
b = progress%256;
} else if(progress < 256*4) {
r = progress%256;
g = 256 - progress%256;
b = 256 - progress%256;
} else if(progress < 256*5) {
r = 255;
g = 0;
b = progress%256;
} else if(progress < 256*6) {
r = 255;
g = progress%256;
b = 256 - progress%256;
} else if(progress < 256*7) {
r = 255;
g = 255;
b = progress%256;
}
lineColorSeekbar.setBackgroundColor(Color.argb(255, r, g, b));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});