Skip to content

Instantly share code, notes, and snippets.

@mancdevcarl
Last active March 25, 2018 14:28
Show Gist options
  • Save mancdevcarl/5602837 to your computer and use it in GitHub Desktop.
Save mancdevcarl/5602837 to your computer and use it in GitHub Desktop.
Custom Arc seekbar / slider
class ArcProgress extends View {
Context cx;
float width;
float height;
float center_x, center_y;
final RectF oval = new RectF();
final RectF touchArea = new RectF();
float sweep = 0;
float left, right;
int percent = 0;
int oldPercent = 0;
public ArcProgress(Context context) {
super(context);
cx = context;
}
public int getPercentage() {
return percent;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setBackgroundColor(0xfff0ebde);
width = (float) getWidth();
height = (float) getHeight();
float radius;
if (width > height) {
radius = height / 3;
} else {
radius = width / 3;
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(0xffd2c8b6);
paint.setStrokeWidth(35);
paint.setStyle(Paint.Style.STROKE);
center_x = width / 2;
center_y = height / 2;
left = center_x - radius;
float top = center_y - radius;
right = center_x + radius;
float bottom = center_y + radius;
Log.d("left", String.valueOf(left));
Log.d("right", String.valueOf(right));
oval.set(left, top, right, bottom);
canvas.drawArc(oval, 180, 180, false, paint);
paint.setStrokeWidth(10);
paint.setColor(0xffe0524d);
canvas.drawArc(oval, 180, sweep, false, paint);
paint.setColor(0xff333333);
paint.setTextSize(30);
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.FILL);
Typeface cFont = Typeface.createFromAsset(cx.getAssets(),
"fonts/bebas.ttf");
paint.setTypeface(cFont);
canvas.drawText("0%", left - 10, center_y + 50, paint);
canvas.drawText("100%", right - 20, center_y + 50, paint);
paint.setTextSize(40);
canvas.drawText(String.valueOf(percent) + "%", right - 20, top, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
} else if (event.getAction() == MotionEvent.ACTION_UP) {
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float xPosition = event.getX();
float yPosition = event.getY();
if (oval.contains(xPosition, yPosition)) {
float x = event.getX() - left;
float s = x * 100;
float b = s / oval.width();
percent = Math.round(b);
sweep = (180 / 100.0f) * (float) percent;
invalidate();
} else {
if (xPosition < left) {
percent = 0;
sweep = (180 / 100.0f) * (float) percent;
invalidate();
}
if (xPosition > right) {
percent = 100;
sweep = (180 / 100.0f) * (float) percent;
invalidate();
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment