This is my code for your solution. Just copy this class and try to understand what your were doing wrong. This view will draw progress bar in center of view.
/**
* Created by GIGAMOLE on 23.01.2016.
*/
public class StrokeProgressBar extends View {
private final static float BAR_STROKE = 10.0f;
private final static float BAR_HEIGHT = 60.0f;
private final static float BAR_PADDING = 100.0f;
private final Paint mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {
{
setDither(true);
setAntiAlias(true);
setColor(Color.BLUE);
setStyle(Style.FILL);
}
};
// private final Paint mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {
// {
// setDither(true);
// setAntiAlias(true);
// setColor(Color.GRAY);
// setStyle(Style.FILL);
// }
// };
private final Paint mBgStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG) {
{
setDither(true);
setAntiAlias(true);
setColor(Color.BLUE);
setStyle(Style.STROKE);
setStrokeWidth(BAR_STROKE);
setStrokeCap(Cap.SQUARE);
}
};
public StrokeProgressBar(final Context context) {
this(context, null);
}
public StrokeProgressBar(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public StrokeProgressBar(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Draw always
setWillNotDraw(false);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
final float height = canvas.getClipBounds().height();
final float width = canvas.getClipBounds().width();
// Background rect
final Rect bgRect = new Rect(
(int) BAR_PADDING,
(int) (height / 2.0f - BAR_HEIGHT / 2.0f),
(int) (width - BAR_PADDING),
(int) (height / 2.0f + BAR_HEIGHT / 2.0f)
);
// Progress bar rect
final Rect progressRect = new Rect(
(int) BAR_PADDING,
(int) (height / 2.0f - BAR_HEIGHT / 2.0f),
(int) ((width - BAR_PADDING) * 0.7f), // 0.7f is the fraction of progress == 70%
(int) (height / 2.0f + BAR_HEIGHT / 2.0f)
);
// At first draw stroke
canvas.drawRect(
bgRect,
mBgStrokePaint
);
// // At second draw bg
// canvas.drawRect(
// bgRect,
// mBgPaint
// );
// At third draw progress
canvas.drawRect(
progressRect,
mProgressPaint
);
}
}