Skip to content

Instantly share code, notes, and snippets.

@ethanliou
Created August 27, 2014 09:39
Show Gist options
  • Save ethanliou/53f9b272d4cd052a1731 to your computer and use it in GitHub Desktop.
Save ethanliou/53f9b272d4cd052a1731 to your computer and use it in GitHub Desktop.
package com.example.drawtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
public class RoundedProgressBar extends View {
Paint mBgPaint;
Paint mProgressPaint;
Point mCenter = null;
RectF mOuterOven = null;
RectF mInnerOven = null;
int THICKNESS = 25;
int mRadius;
float mProgress = 0.9f;
public RoundedProgressBar(Context context) {
super(context);
float density = getResources().getDisplayMetrics().density;
THICKNESS *= density;
setBackgroundColor(Color.TRANSPARENT);
mBgPaint = new Paint();
mBgPaint.setStyle(Paint.Style.FILL);
mBgPaint.setColor(Color.rgb(36, 33, 38));
mBgPaint.setAntiAlias(true);
mProgressPaint = new Paint(mBgPaint);
mProgressPaint.setColor(Color.RED);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mOuterOven = new RectF(0, 0, w, w);
mInnerOven = new RectF(THICKNESS, THICKNESS, w - THICKNESS, w - THICKNESS);
mCenter = new Point(w / 2, w / 2);
mRadius = w/2-THICKNESS/2;
mProgressPaint.setShader(new LinearGradient(0,0,w,0,Color.rgb(109,198,34),Color.rgb(233, 84, 47),Shader.TileMode.CLAMP));
}
@Override
protected void onDraw(Canvas canvas) {
drawArc(canvas, 120, 300, mBgPaint);
drawArc(canvas, 120, 300 * mProgress, mProgressPaint);
super.onDraw(canvas);
}
private void drawArc(Canvas canvas, float startAngle, float sweepDegrees,
Paint paint) {
Path path = new Path();
Point startPoint = calculatePointOnArc(mCenter.x, mCenter.y, mRadius,
startAngle);
Point endPoint = calculatePointOnArc(mCenter.x, mCenter.y, mRadius,
startAngle + sweepDegrees);
path.arcTo(mOuterOven, startAngle, sweepDegrees);
path.arcTo(mInnerOven, startAngle + sweepDegrees, -sweepDegrees);
path.addCircle(startPoint.x, startPoint.y, THICKNESS / 2,
Path.Direction.CW);
path.addCircle(endPoint.x, endPoint.y, THICKNESS / 2,
Path.Direction.CW);
path.close();
canvas.drawPath(path, paint);
}
// this is to calculate the end points of the arc
private Point calculatePointOnArc(int circleCeX, int circleCeY,
int circleRadius, float endAngle) {
Point point = new Point();
double endAngleRadian = endAngle * (Math.PI / 180);
int pointX = (int) Math.round((circleCeX + circleRadius
* Math.cos(endAngleRadian)));
int pointY = (int) Math.round((circleCeY + circleRadius
* Math.sin(endAngleRadian)));
point.x = pointX;
point.y = pointY;
return point;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment