package com.furlingtech.printer.utils;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import com.furlingtech.printer.R;
/**
* @author lpy
* @date 2020-09-15 13:27
*/
public class MyProgressBar extends View {
/**
* 默认已完成颜色
*/
private final int DEFAULT_FINISHED_COLOR;
/**
* 默认未完成颜色
*/
private final int DEFAULT_BACKGROUND_COLOR;
/**
* 进度条上奥特曼小人
*/
Bitmap icon;
/**
* 进度条背景矩形区域
*/
private RectF mBackgroundRectF = new RectF(0, 0, 0, 0);
/**
* 已完成进度条所在矩形区域
*/
private RectF mReachedRectF = new RectF(0, 0, 0, 0);
/**
* 进度条最大值
*/
private float mMax = 100;
/**
* 进度条当前进度值
*/
private int mProgress;
private Paint mPaint;
public MyProgressBar(Context context) {
this(context, null);
}
public MyProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
DEFAULT_FINISHED_COLOR = ContextCompat.getColor(context, R.color.colorAccent);
DEFAULT_BACKGROUND_COLOR = ContextCompat.getColor(context, android.R.color.white);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomProgressBar, 0, 0);
mProgress = typedArray.getInt(R.styleable.CustomProgressBar_android_progress, 0);
init();
}
private void init() {
icon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_progressbar);
initPainters();
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
//控件宽度
int width = getMeasuredWidth();
//控件高度
int height = getMeasuredHeight();
//绘制进度条背景矩形区域
mPaint.setColor(DEFAULT_BACKGROUND_COLOR);
mBackgroundRectF.left = 0;
mBackgroundRectF.top = height / 2f;
mBackgroundRectF.right = width;
mBackgroundRectF.bottom = height;
canvas.drawRect(mBackgroundRectF, mPaint);
//根据进度绘制完成进度矩形区域
float reachedRectfWidth = mProgress / mMax * width;
mPaint.setColor(DEFAULT_FINISHED_COLOR);
mReachedRectF.left = 0;
mReachedRectF.top = height / 2f;
mReachedRectF.right = reachedRectfWidth;
mReachedRectF.bottom = height;
canvas.drawRect(mReachedRectF, mPaint);
int iconWidth = icon.getWidth();
if (reachedRectfWidth <= iconWidth) {
canvas.drawBitmap(icon, 0, 0, mPaint);
} else if (mProgress >= mMax) {
canvas.drawBitmap(icon, width - iconWidth, 0, mPaint);
} else {
canvas.drawBitmap(icon, reachedRectfWidth - iconWidth, 0, mPaint);
}
}
/**
* 初始化画笔
*/
private void initPainters() {
//抗锯齿
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//防抖动
mPaint.setAntiAlias(true);
mPaint.setStrokeCap(Paint.Cap.ROUND);
}
public void setProgress(int progress) {
mProgress = progress;
postInvalidate();
}
}
Android 自定义ProgressBar
最新推荐文章于 2024-05-07 18:00:19 发布