2021-10-24

自适应大小的进度条

根据View宽度来绘制进度,极简风格。

先在onDraw方法里获取View的宽度

int width = getWidth();
int height = getHeight();

重要的一部分来了,计算绘制时所需宽度

//View宽度的百分之一
float bfzy = (float) width / 100;
//绘制进度所需宽度,mProgress为进度值
int sxkd = (int) (bfzy * mProgress);

这里是全部代码:

import android.content.Context;
import android.graphics.*;
import android.view.View;

public class MyProgressView extends View {
//定义进度条的画笔
private Paint mPaint;
//进度
private float mProgress;
//前景色
private int ForegroundColor;
//背景色
private int BackgroundColor;
public MyProgressView(Context context) {
super(context);
mProgress = 0f;
mPaint = new Paint();
ForegroundColor = 0xff888888;
BackgroundColor = 0Xfff0f0f0;
}
@Override
public void onDraw(Canvas canvas) {        //设置背景色
mPaint.setColor(BackgroundColor);
Rect dst = new Rect();
dst.left = 0;
dst.top = 0;
dst.right = getWidth();
dst.bottom = getHeight();
//画背景
canvas.drawRect(dst, mPaint);
if (mProgress > 0) {
//进度值 > 0 时绘制
float bfzy = (float) getWidth() / 100;
int sxkd = (int) (bfzy * mProgress);
//设置前景色
mPaint.setColor(ForegroundColor);
Rect dst1 = new Rect();         dst1.left = 0;
dst1.top = 0;
dst1.right = sxkd;
dst1.bottom = getHeight();
//画进度
canvas.drawRect(dst1, mPaint);
}
}

//设置前景色
public void setForegroundColor(int co) {
this.ForegroundColor = co;
invalidate();
}
//设置背景色
public void setBackgroundColor(int co) {
this.BackgroundColor = co;
invalidate();
}
//获取前景色
public int getForegroundColor() {
return this.ForegroundColor;
}
//获取背景色
public int getBackgroundColor() {  return this.BackgroundColor;
}
//设置当前进度值
public void setProgress(float pr) {
this.mProgress = pr;
invalidate();
}
//获取进度值百分比
public float getProgress() {
return this.mProgress;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Heng:X

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值