Round edge progress bar in Android - android

I'm new to android and I'm trying to make a circular progress bar with nice style.
Therefore I found a very simple solution how to make a circular progress bar, using shape="ring"
My code is
mainpage_layout.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="250dp"
android:layout_height="250dp"
android:max="100"
android:progress="80"
android:rotation="-90"
android:layout_centerInParent="true"
android:progressDrawable="#drawable/circular_progress" />
</RelativeLayout>
circular_progress.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:useLevel="true"
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="7dp" >
<solid android:color="#color/colorPrimary" />
</shape>
and its looks like this
I want to style it like this awesome progress bar :
Edit
This is the padded background for the progress bar that i want to make
to add some background to the progress bar and to make the edges of it be rounded instead of squared.
Is there is an easy solution to do that or should I must give up on using this shape="ring" thing.
Thank you very much,
Asaf.

You can use https://github.com/korre/android-circular-progress-bar
There you have a method useRoundedCorners you need to pass false to make it not round by-default it is round at the edge
There is a custom class you can actually take from that library(It is more than enough),
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
public class CircularProgressBar extends View {
private int mViewWidth;
private int mViewHeight;
private final float mStartAngle = -90; // Always start from top (default is: "3 o'clock on a watch.")
private float mSweepAngle = 0; // How long to sweep from mStartAngle
private float mMaxSweepAngle = 360; // Max degrees to sweep = full circle
private int mStrokeWidth = 20; // Width of outline
private int mAnimationDuration = 400; // Animation duration for progress change
private int mMaxProgress = 100; // Max progress to use
private boolean mDrawText = true; // Set to true if progress text should be drawn
private boolean mRoundedCorners = true; // Set to true if rounded corners should be applied to outline ends
private int mProgressColor = Color.BLACK; // Outline color
private int mTextColor = Color.BLACK; // Progress text color
private final Paint mPaint; // Allocate paint outside onDraw to avoid unnecessary object creation
public CircularProgressBar(Context context) {
this(context, null);
}
public CircularProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircularProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
initMeasurments();
drawOutlineArc(canvas);
if (mDrawText) {
drawText(canvas);
}
}
private void initMeasurments() {
mViewWidth = getWidth();
mViewHeight = getHeight();
}
private void drawOutlineArc(Canvas canvas) {
final int diameter = Math.min(mViewWidth, mViewHeight) - (mStrokeWidth * 2);
final RectF outerOval = new RectF(mStrokeWidth, mStrokeWidth, diameter, diameter);
mPaint.setColor(mProgressColor);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setAntiAlias(true);
mPaint.setStrokeCap(mRoundedCorners ? Paint.Cap.ROUND : Paint.Cap.BUTT);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawArc(outerOval, mStartAngle, mSweepAngle, false, mPaint);
}
private void drawText(Canvas canvas) {
mPaint.setTextSize(Math.min(mViewWidth, mViewHeight) / 5f);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setStrokeWidth(0);
mPaint.setColor(mTextColor);
// Center text
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((mPaint.descent() + mPaint.ascent()) / 2)) ;
canvas.drawText(calcProgressFromSweepAngle(mSweepAngle) + "%", xPos, yPos, mPaint);
}
private float calcSweepAngleFromProgress(int progress) {
return (mMaxSweepAngle / mMaxProgress) * progress;
}
private int calcProgressFromSweepAngle(float sweepAngle) {
return (int) ((sweepAngle * mMaxProgress) / mMaxSweepAngle);
}
/**
* Set progress of the circular progress bar.
* #param progress progress between 0 and 100.
*/
public void setProgress(int progress) {
ValueAnimator animator = ValueAnimator.ofFloat(mSweepAngle, calcSweepAngleFromProgress(progress));
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(mAnimationDuration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mSweepAngle = (float) valueAnimator.getAnimatedValue();
invalidate();
}
});
animator.start();
}
public void setProgressColor(int color) {
mProgressColor = color;
invalidate();
}
public void setProgressWidth(int width) {
mStrokeWidth = width;
invalidate();
}
public void setTextColor(int color) {
mTextColor = color;
invalidate();
}
public void showProgressText(boolean show) {
mDrawText = show;
invalidate();
}
/**
* Toggle this if you don't want rounded corners on progress bar.
* Default is true.
* #param roundedCorners true if you want rounded corners of false otherwise.
*/
public void useRoundedCorners(boolean roundedCorners) {
mRoundedCorners = roundedCorners;
invalidate();
}
}
Then you can set the view in your xml like
<yourPackageName.CircularProgressBar
android:id="#+id/circularProgress"
android:layout_width="180dp"
android:layout_height="180dp"/>
And in your class you can call it like this,
CircularProgressBar circularProgressBar = (CircularProgressBar) findViewById(R.id.circularProgress);
circularProgressBar.setProgress(50);
circularProgressBar.setProgressColor(Color.BLUE);

Related

Indeterminate ProgressBar with round edges

I am simply trying to customize the default indeterminate progressbar. Please how do I go from this
<ProgressBar
android:layout_width="100dp"
android:layout_height="100dp"
android:indeterminate="true"
android:indeterminateTintMode="src_atop"
android:indeterminateTint="#FFFFFF"/>
asper:
to this (easily):
Update: seems the question isn't a bit straight forward so I have added .gifs below to further explain, I want this (with sharp edges): to simply become this (with round edges):
sorry about the color change, that was the best google turned up
You can use https://github.com/korre/android-circular-progress-bar
There you have a method useRoundedCorners you need to pass false to make it not round by-default it is round at the edge
There is a custom class you can actually take from that library(It is more than enough),
public class CircularProgressBar extends View {
private int mViewWidth;
private int mViewHeight;
private final float mStartAngle = -90; // Always start from top (default is: "3 o'clock on a watch.")
private float mSweepAngle = 0; // How long to sweep from mStartAngle
private float mMaxSweepAngle = 360; // Max degrees to sweep = full circle
private int mStrokeWidth = 20; // Width of outline
private int mAnimationDuration = 400; // Animation duration for progress change
private int mMaxProgress = 100; // Max progress to use
private boolean mDrawText = true; // Set to true if progress text should be drawn
private boolean mRoundedCorners = true; // Set to true if rounded corners should be applied to outline ends
private int mProgressColor = Color.BLACK; // Outline color
private int mTextColor = Color.BLACK; // Progress text color
private final Paint mPaint; // Allocate paint outside onDraw to avoid unnecessary object creation
public CircularProgressBar(Context context) {
this(context, null);
}
public CircularProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircularProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
initMeasurments();
drawOutlineArc(canvas);
if (mDrawText) {
drawText(canvas);
}
}
private void initMeasurments() {
mViewWidth = getWidth();
mViewHeight = getHeight();
}
private void drawOutlineArc(Canvas canvas) {
final int diameter = Math.min(mViewWidth, mViewHeight) - (mStrokeWidth * 2);
final RectF outerOval = new RectF(mStrokeWidth, mStrokeWidth, diameter, diameter);
mPaint.setColor(mProgressColor);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setAntiAlias(true);
mPaint.setStrokeCap(mRoundedCorners ? Paint.Cap.ROUND : Paint.Cap.BUTT);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawArc(outerOval, mStartAngle, mSweepAngle, false, mPaint);
}
private void drawText(Canvas canvas) {
mPaint.setTextSize(Math.min(mViewWidth, mViewHeight) / 5f);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setStrokeWidth(0);
mPaint.setColor(mTextColor);
// Center text
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((mPaint.descent() + mPaint.ascent()) / 2)) ;
canvas.drawText(calcProgressFromSweepAngle(mSweepAngle) + "%", xPos, yPos, mPaint);
}
private float calcSweepAngleFromProgress(int progress) {
return (mMaxSweepAngle / mMaxProgress) * progress;
}
private int calcProgressFromSweepAngle(float sweepAngle) {
return (int) ((sweepAngle * mMaxProgress) / mMaxSweepAngle);
}
/**
* Set progress of the circular progress bar.
* #param progress progress between 0 and 100.
*/
public void setProgress(int progress) {
ValueAnimator animator = ValueAnimator.ofFloat(mSweepAngle, calcSweepAngleFromProgress(progress));
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(mAnimationDuration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mSweepAngle = (float) valueAnimator.getAnimatedValue();
invalidate();
}
});
animator.start();
}
public void setProgressColor(int color) {
mProgressColor = color;
invalidate();
}
public void setProgressWidth(int width) {
mStrokeWidth = width;
invalidate();
}
public void setTextColor(int color) {
mTextColor = color;
invalidate();
}
public void showProgressText(boolean show) {
mDrawText = show;
invalidate();
}
/**
* Toggle this if you don't want rounded corners on progress bar.
* Default is true.
* #param roundedCorners true if you want rounded corners of false otherwise.
*/
public void useRoundedCorners(boolean roundedCorners) {
mRoundedCorners = roundedCorners;
invalidate();
}}
Then you can set the view in your xml like
<yourPackageName.CircularProgressBar
android:id="#+id/circularProgress"
android:layout_width="180dp"
android:layout_height="180dp"/>
And in your class you can call it like this,
CircularProgressBar circularProgressBar = (CircularProgressBar)
findViewById(R.id.circularProgress);
circularProgressBar.setProgress(50);
circularProgressBar.setProgressColor(Color.BLUE);

Removing the Background border from a ProgressBar

I am trying to achieve Pie Progress without border
without center circle and it's progress .. So I tried multiple ways to achieve it in ProgressBar
Both my approach shows a border around the PIE
I simply want to remove the border Or I want the below circle to be of exact size.
1st Approach
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#color/grey_lightest"/>
</shape>
</item>
<item>
<shape
android:innerRadiusRatio="100"
android:shape="ring"
android:thicknessRatio="2.5"
android:useLevel="true">
<gradient
android:centerColor="#color/orange_above_avg"
android:endColor="#color/orange_above_avg"
android:startColor="#color/orange_above_avg"
android:type="sweep"
android:useLevel="false" />
</shape>
</item>
</layer-list>
2nd Approach
I created seperate background and progressDrawable but still same result..
It's not exact solution to your problem but you can use customview to achieve it .
Here is a reference which I picked from some project (so an't give proper credit)
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import in.eightfolds.soundvision.R;
public class CustomProgress extends View {
private static final String TAG = "CustomProgress";
private float maxWidth, maxHight;
private PointF centerPoint;
private float radius;
float progressSize = 0f;
private Path path;
private RectF oval;
private Paint mcirclePaint;
private Paint mTextPaint;
private int progress = 0;
private Paint mBackCirclePaint;
private int paintStrokeWidth=40;
public CustomProgress(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomProgress(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomProgress(Context context) {
super(context);
init();
}
private void init() {
centerPoint = new PointF();
path = new Path();
mcirclePaint = new Paint();
mcirclePaint.setColor(Color.RED);
mcirclePaint.setStrokeWidth(paintStrokeWidth);
// paint.setDither(true);
mcirclePaint.setAntiAlias(true);
mcirclePaint.setStyle(Paint.Style.STROKE);
mBackCirclePaint = new Paint();
mBackCirclePaint.setColor(Color.DKGRAY);
mBackCirclePaint.setStrokeWidth(paintStrokeWidth);
// paint.setDither(true);
mBackCirclePaint.setAntiAlias(true);
mBackCirclePaint.setStyle(Paint.Style.STROKE);
oval = new RectF();
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
// mTextPaint.setColor(getResources().getColor(
// android.R.color.holo_blue_dark));
mTextPaint.setColor(Color.RED);
mTextPaint.setStrokeWidth(1);
mTextPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.setTextSize(60);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(centerPoint.x, centerPoint.y, radius,
mBackCirclePaint);
// mcirclePaint.setColor(Color.RED);
canvas.drawArc(oval, -90, progressSize, false, mcirclePaint);
// paint.setTextSize(20);
// canvas.drawCircle(centerPoint.x, centerPoint.y, 2, mcirclePaint);
if (progress > 0) {
canvas.drawText(progress + "%", centerPoint.x, centerPoint.y
+ mTextPaint.descent(), mTextPaint);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
Log.v(TAG, "" + changed);
if (getMeasuredWidth() < getMeasuredHeight()) {
maxWidth = getMeasuredWidth();
maxHight = getMeasuredHeight();
centerPoint.x = maxWidth / 2;
centerPoint.y = maxHight / 2;
} else {
maxWidth = getMeasuredHeight();
maxHight = getMeasuredWidth();
centerPoint.x = maxHight / 2;
centerPoint.y = maxWidth / 2;
}
setUp();
}
private void setUp() {
if (maxWidth > maxHight) {
radius = maxHight / 4;
} else {
radius = maxWidth / 4;
}
path.addCircle(maxWidth / 2,
maxHight / 2, radius,
Path.Direction.CW);
oval.set(centerPoint.x - radius,
centerPoint.y - radius,
centerPoint.x + radius,
centerPoint.y + radius);
}
public void upDateProgress(int progress) {
mcirclePaint.setColor(getResources().getColor(R.color.themeColor));
mTextPaint.setColor(getResources().getColor(R.color.themeColor));
this.progress = progress;
float i = 360f / 100f;
progressSize = (float) (i * progress);
Log.d(TAG, progress + "<----progress---->" + progressSize);
invalidate();
}
public int getProgress() {
return progress;
}
}
Use this in layout file and use upDateProgress to change progress .
Change widths and colors to your own . If you want text, then place a textview in center to this customview

Set seekbar thumb above seekbar line

In my Android app, I have to customize a seekbar and I wonder how I can set a seekbar thumb above its progress line instead of center by default?
You can check it out Discrete Seekbar
seekBar.setMin(0);
seekBar.setMax(yourArray.length);
seekBar.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() {
int onProgressChanged =0;
#Override
public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
onProgressChanged = value;
}
#Override
public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
}
});
I looked for this info in many posts and get some ideas from there and here, and created SeekBayHint, which creates text of progress above arrow:
SeekBar
MainClass:
package your_package;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import your_package.R;
public class SeekBarHint extends android.support.v7.widget.AppCompatSeekBar {
private Paint mTextPaint;
private Rect mTextBounds = new Rect();
private Bitmap mBitmapIconArrowDown;
/** for this class yPosition must be as minHeight in layoutFile for this seekBar*/
private static int sTextYPositionIndent = 20;
private float mTextSizeDecrease = 1.75f;
public static void setTextYPositionIndent(int textYPositionIndent) {
sTextYPositionIndent = textYPositionIndent;
}
public SeekBarHint(Context context) {
super(context);
mBitmapIconArrowDown = BitmapFactory.decodeResource(context.getResources(),
R.drawable.progress_seek_bar_arrow_down);
mTextPaint = new Paint();
mTextPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
public SeekBarHint(Context context, AttributeSet attrs) {
super(context, attrs);
mBitmapIconArrowDown = BitmapFactory.decodeResource(context.getResources(),
R.drawable.progress_seek_bar_arrow_down);
mTextPaint = new Paint();
mTextPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
public SeekBarHint(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mBitmapIconArrowDown = BitmapFactory.decodeResource(context.getResources(),
R.drawable.progress_seek_bar_arrow_down);
mTextPaint = new Paint();
mTextPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
#Override
protected synchronized void onDraw(Canvas canvas) {
// first draw the regular progress bar, then custom draw our textString
super.onDraw(canvas);
// now progress position and convert to textString.
String textString = Integer.toString(getProgress()) + "%";
// now get size of seek bar.
float width = getWidth();
float height = getHeight();
// set textString size.
mTextPaint.setTextSize(height / mTextSizeDecrease);
// get size of textString.
mTextPaint.getTextBounds(textString, 0, textString.length(), mTextBounds);
// calculate where to start printing textString.
float position = (width / getMax()) * getProgress();
// get start and end points of where textString will be printed.
float textXStart = position - mTextBounds.centerX();
float textXEnd = position + mTextBounds.centerX();
// check does not start drawing text outside seek bar.
if (textXStart < 0)
textXStart = 0;
if (textXEnd > width)
textXStart -= (textXEnd - width);
// calculate y textString print position.
float yPosition = (height / 2) - mTextBounds.centerY();
canvas.drawText(textString, textXStart, yPosition - sTextYPositionIndent, mTextPaint);
// arrow draw logic
// check does not start drawing arrow outside seek bar
int seekBarAbsoluteWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int thumbPos = (getPaddingLeft() / 2) + (seekBarAbsoluteWidth * getProgress() / getMax());
// set height and width for new bitmap
int arrowHeight = Math.round(mTextBounds.height()/2f);
int arrowWidth = mTextBounds.width()/3;
Bitmap scaledBitmapIconArrowDown = Bitmap
.createScaledBitmap(mBitmapIconArrowDown, arrowWidth, arrowHeight, true);
canvas.drawBitmap(scaledBitmapIconArrowDown, thumbPos, yPosition, null);
}
}
To support different dimension use this code in OnCreateView (if seekBar used in fragment) or in OnCreate (if seekBar used in activity):
DisplayMetrics metrics = getResources().getDisplayMetrics();
int dpi = metrics.densityDpi;
if(dpi < 230){
SeekBarHint.setTextYPositionIndent(5);
} else if (dpi < 310){
SeekBarHint.setTextYPositionIndent(15);
} else if (dpi < 470){
SeekBarHint.setTextYPositionIndent(10);
}

Android uber ping request animation or component

Can any one suggest me how to do circle animation and progress button like Uber driver pickup request in Android. If you can provide some code that will be good.
You can refer to this.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import com.circularseekbar.R;
public class CircularProgressBar extends View {
private Context mContext;
private Paint circleColor, innerColor, circleRing;
private int angle = 0, startAngle = 270, barWidth = 50, maxProgress = 100;
private int width, height, progress=1, tmpProgress=1, progressPercent;
private float innerRadius, outerRadius, adjustmentFactor=100;//The radius of the inner circle
private float cx, cy; //The circle's center X, Y coordinate
private float left, right, top, bottom, startPointX, startPointY, markPointX, markPointY;
private float dx, dy;//The X and Y coordinate for the top left corner of the marking drawable
private Bitmap progressMark, progressMarkPressed;
private RectF rect = new RectF();
{
circleColor = new Paint();
innerColor = new Paint();
circleRing = new Paint();
circleColor.setColor(Color.parseColor("#ff33b5e5")); // Set default
// progress
// color to holo
// blue.
innerColor.setColor(Color.BLACK); // Set default background color to
// black
circleRing.setColor(Color.GRAY);// Set default background color to Gray
circleColor.setAntiAlias(true);
innerColor.setAntiAlias(true);
circleRing.setAntiAlias(true);
circleColor.setStrokeWidth(25);
innerColor.setStrokeWidth(15);
circleRing.setStrokeWidth(10);
circleColor.setStyle(Paint.Style.FILL);
}
public CircularProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
}
public CircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public CircularProgressBar(Context context) {
super(context);
mContext = context;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getWidth(); // Get View Width
height = getHeight();// Get View Height
int size = (width > height) ? height : width; // Choose the smaller
// between width and
// height to make a
// square
cx = width / 2; // Center X for circle
cy = height / 2; // Center Y for circle
outerRadius = size / 2; // Radius of the outer circle
innerRadius = outerRadius - barWidth; // Radius of the inner circle
left = cx - outerRadius; // Calculate left bound of our rect
right = cx + outerRadius;// Calculate right bound of our rect
top = cy - outerRadius;// Calculate top bound of our rect
bottom = cy + outerRadius;// Calculate bottom bound of our rect
startPointX = cx; // 12 O'clock X coordinate
startPointY = cy - outerRadius;// 12 O'clock Y coordinate
markPointX = startPointX;// Initial locatino of the marker X coordinate
markPointY = startPointY;// Initial locatino of the marker Y coordinate
rect.set(left, top, right, bottom); // assign size to rect
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawCircle(cx, cy, outerRadius, circleRing);
canvas.drawArc(rect, startAngle, angle, true, circleColor);
canvas.drawCircle(cx, cy, innerRadius, innerColor);
super.onDraw(canvas);
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
//System.out.println("Angel "+angle);
this.angle = angle;
float donePercent = (((float) this.angle) / 360) * 100;
float progress = (donePercent / 100) * getMaxProgress();
setProgressPercent(Math.round(donePercent));
setProgress(Math.round(progress));
}
public int getBarWidth() {
return barWidth;
}
public void setBarWidth(int barWidth) {
this.barWidth = barWidth;
}
public int getMaxProgress() {
return maxProgress;
}
public void setMaxProgress(int maxProgress) {
this.maxProgress = maxProgress;
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
if (this.progress != progress) {
this.progress = progress;
int newPercent = (this.progress * 100) / this.maxProgress;
int newAngle = (newPercent * 360) / 100;
this.setAngle(newAngle);
this.setProgressPercent(newPercent);
}
}
long mAnimStartTime;
Handler mHandler = new Handler();
Runnable mTick = new Runnable() {
public void run() {
invalidate();
update();
mHandler.postDelayed(this, 100); // 20ms == 60fps
}
};
public void update(){
if(IS_ACTIVE){
setProgress(tmpProgress);
if(tmpProgress>maxProgress){
stopAnimation();
}
tmpProgress++;
}
}
boolean IS_ACTIVE=false;
public void startAnimation() {
IS_ACTIVE=true;
tmpProgress=1;
mHandler.removeCallbacks(mTick);
mHandler.post(mTick);
}
public void stopAnimation() {
IS_ACTIVE=false;
progress=1;
mHandler.removeCallbacks(mTick);
}
public int getProgressPercent() {
return progressPercent;
}
public void setProgressPercent(int progressPercent) {
this.progressPercent = progressPercent;
}
public void setRingBackgroundColor(int color) {
circleRing.setColor(color);
}
public void setBackGroundColor(int color) {
innerColor.setColor(color);
}
public void setProgressColor(int color) {
circleColor.setColor(color);
}
public float getAdjustmentFactor() {
return adjustmentFactor;
}
public void setAdjustmentFactor(float adjustmentFactor) {
this.adjustmentFactor = adjustmentFactor;
}
}

filling a circle gradually from bottom to top android

I have created a circle with a stroke and white background using xml. How can this be filled gradually from bottom to top on user actions(e.g. on successive button press)?
Is there any free library which can be used to achieve similar thing?
I created a Custom View class that will do what you want. There are four custom attributes that can be set in your layout xml:
fillColor, color - Sets the color of the fill area. Default is Color.WHITE.
strokeColor, color - Sets the color of the bounding circle. Default is Color.BLACK.
strokeWidth, float - Sets the thickness of the bounding circle. Default is 1.0.
value, integer: 0-100 - Sets the value for the fill area. Default is 0.
Please note that these attributes must have the custom prefix in lieu of the android prefix in your layout xml. The root View should also contain the custom xml namespace. (See the example below.) The other standard View attributes - such as layout_width, background, etc. - are available.
First, the CircleFillView class:
public class CircleFillView extends View
{
public static final int MIN_VALUE = 0;
public static final int MAX_VALUE = 100;
private PointF center = new PointF();
private RectF circleRect = new RectF();
private Path segment = new Path();
private Paint strokePaint = new Paint();
private Paint fillPaint = new Paint();
private int radius;
private int fillColor;
private int strokeColor;
private float strokeWidth;
private int value;
public CircleFillView(Context context)
{
this(context, null);
}
public CircleFillView(Context context, AttributeSet attrs)
{
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CircleFillView,
0, 0);
try
{
fillColor = a.getColor(R.styleable.CircleFillView_fillColor, Color.WHITE);
strokeColor = a.getColor(R.styleable.CircleFillView_strokeColor, Color.BLACK);
strokeWidth = a.getFloat(R.styleable.CircleFillView_strokeWidth, 1f);
value = a.getInteger(R.styleable.CircleFillView_value, 0);
adjustValue(value);
}
finally
{
a.recycle();
}
fillPaint.setColor(fillColor);
strokePaint.setColor(strokeColor);
strokePaint.setStrokeWidth(strokeWidth);
strokePaint.setStyle(Paint.Style.STROKE);
}
public void setFillColor(int fillColor)
{
this.fillColor = fillColor;
fillPaint.setColor(fillColor);
invalidate();
}
public int getFillColor()
{
return fillColor;
}
public void setStrokeColor(int strokeColor)
{
this.strokeColor = strokeColor;
strokePaint.setColor(strokeColor);
invalidate();
}
public int getStrokeColor()
{
return strokeColor;
}
public void setStrokeWidth(float strokeWidth)
{
this.strokeWidth = strokeWidth;
strokePaint.setStrokeWidth(strokeWidth);
invalidate();
}
public float getStrokeWidth()
{
return strokeWidth;
}
public void setValue(int value)
{
adjustValue(value);
setPaths();
invalidate();
}
public int getValue()
{
return value;
}
private void adjustValue(int value)
{
this.value = Math.min(MAX_VALUE, Math.max(MIN_VALUE, value));
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
center.x = getWidth() / 2;
center.y = getHeight() / 2;
radius = Math.min(getWidth(), getHeight()) / 2 - (int) strokeWidth;
circleRect.set(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
setPaths();
}
private void setPaths()
{
float y = center.y + radius - (2 * radius * value / 100 - 1);
float x = center.x - (float) Math.sqrt(Math.pow(radius, 2) - Math.pow(y - center.y, 2));
float angle = (float) Math.toDegrees(Math.atan((center.y - y) / (x - center.x)));
float startAngle = 180 - angle;
float sweepAngle = 2 * angle - 180;
segment.rewind();
segment.addArc(circleRect, startAngle, sweepAngle);
segment.close();
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawPath(segment, fillPaint);
canvas.drawCircle(center.x, center.y, radius, strokePaint);
}
}
Now, for the custom xml attributes to work, you will need to put the following file in the /res/values folder of your project.
attrs.xml:
<resources>
<declare-styleable name="CircleFillView" >
<attr name="fillColor" format="color" />
<attr name="strokeColor" format="color" />
<attr name="strokeWidth" format="float" />
<attr name="value" format="integer" />
</declare-styleable>
</resources>
Following are the files for a simple demonstration app, where the CircleFillView's value is controlled with a SeekBar.
The layout file for our Activity, main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.circlefill"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<com.example.circlefill.CircleFillView
android:id="#+id/circleFillView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ffffff"
custom:fillColor="#6bcae2"
custom:strokeColor="#75b0d0"
custom:strokeWidth="20"
custom:value="65" />
<SeekBar android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And, the MainActivity class:
public class MainActivity extends Activity
{
CircleFillView circleFill;
SeekBar seekBar;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
circleFill = (CircleFillView) findViewById(R.id.circleFillView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setProgress(circleFill.getValue());
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
if (fromUser)
circleFill.setValue(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
}
);
}
}
And a screenshot of the demo app:

Categories

Resources