看到了一个App自定义的SeekBar很有趣,尝试着自己做一个。
不废话,先上图,看是否是你期望的:
增加了背景图片的自定义,增加了Thumb的自定义。当然还有动画效果。会动画滑动到附近的点。具体代码稍后奉上...
啊。。。乱七八糟事儿太多,这几天都没时间整理
这个demo的点可以自定义数量,并增加回调。我就不写原理了...直接把代码传上去...有时间再写...
也可以尝试IndicatorSeekBar这个,GitHub上的,2017年出的,写这篇博客是2016年。那时候还没有....
源码已发布,地址:https://download.csdn.net/download/explorerqp/11373353
首先需要画出seekbar的背景drawable:
package com.zkbc.tougu.demo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
/**
* 自定义seekBar背景图
* Created by Rock Lee on 2016/6/21.
*/
public class MySeekBarDrawable extends Drawable {
int pointCount;
int startColor;
int centerColor;
int endColor;
private Paint paint;//画笔(背景)
LinearGradient shader;
private Paint paintCircle;//画笔-外圆
private Paint paintCircleCenter;//画笔-内圆
RectF rectF;//矩形上下左右的坐标
int colors[] = new int[3];//三个颜色渐变(shader)
float positions[] = new float[3];//渐变色的三个点(shader)
public MySeekBarDrawable(int pointCount, int startColor, int centerColor, int endColor) {
this.pointCount = pointCount * 2;//增加两点之间的中线
this.startColor = startColor;
this.centerColor = centerColor;
this.endColor = endColor;
paint = new Paint();
paintCircle = new Paint();
paintCircleCenter = new Paint();
rectF = new RectF();
}
@Override
public void draw(Canvas canvas) {
final Rect bounds = getBounds();
// 第1个点
colors[0] = startColor;
positions[0] = 0;
// 第2个点
colors[1] = centerColor;
positions[1] = 0.5f;
// 第3个点
colors[2] = endColor;
positions[2] = 1;
//是否有中间色
if (centerColor == 0) {
shader = new LinearGradient(0f, 0f, bounds.width(), bounds.height(), startColor, endColor, Shader.TileMode.MIRROR);
} else {
shader = new LinearGradient(0f, 0f, bounds.width(), bounds.height(), colors, positions, Shader.TileMode.MIRROR);
}
paint.setShader(shader);
paint.setStrokeCap(Paint.Cap.ROUND);// 圆角
paint.setAntiAlias(true); // 消除锯齿
paintCircle.setShader(shader);
// paintCircle.setStyle(Paint.Style.STROKE); // 设置空心
// paintCircle.setStrokeWidth(bounds.height()/2); // 设置笔画的宽度
paintCircle.setAntiAlias(true); // 消除锯齿
paintCircleCenter.setAntiAlias(true); // 消除锯齿
paintCircleCenter.setColor(Color.WHITE);
float lineHeight = bounds.height()/4.0f;
rectF.set(0, bounds.centerY() - lineHeight, bounds.width(), bounds.centerY() + lineHeight);
//绘制圆角矩形
canvas.drawRoundRect(rectF, lineHeight, lineHeight, paint);
float section = (float) bounds.width() / pointCount;
for (int i = 1; i < pointCount; i++) {
paint.setShader(null);
paint.setColor(Color.WHITE);
// paint.setStrokeWidth(1);
float cx = section * i;//X轴圆心坐标
if (i % 2 == 0) {
canva