自定义view 画百分比
程序员文章站
2024-02-05 20:39:52
...
对于自定义view,我是一知半解,正在学习中,将自己实验过的自定义view记录下来,防止自己多次走同样的坑
效果献上一个效果图
自定义view的实现
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by wxt on 2017/5/12.
*/
public class CircleView2 extends View{
private Paint mPaint;
private Context mContext;
//内圆的半径
private int innerCircle=40;
//圆圈的宽度
private int ringWidth=4;
//设置圆圈的百分比
private float mPercent;
public CircleView2(Context context) {
this(context, null);
}
public CircleView2(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
mPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
int center = getWidth() / 2;
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);//下面修改过paint的style,不在这里设置容易出出现paint的style不管用的情况,
innerCircle = dip2px(mContext, 50);
ringWidth = dip2px(mContext, 4);
mPaint.setARGB(155, 167, 190, 206);
mPaint.setStrokeWidth(2);//设置2px的边边
canvas.drawCircle(center, center, innerCircle, mPaint);
mPaint.setARGB(255, 212, 225, 233);
mPaint.setStrokeWidth(ringWidth);//设置ringWidth宽度的圆环
canvas.drawCircle(center, center, innerCircle + 1 + ringWidth / 2, mPaint);
mPaint.setStrokeWidth(2);//设置2px的边边
canvas.drawCircle(center, center, innerCircle + ringWidth + 1, mPaint);
RectF rectF = new RectF();
int circleY = (getWidth() - innerCircle * 2 - ringWidth) / 2;
rectF.set(circleY, circleY, getWidth() - circleY, getHeight() - circleY);
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(ringWidth);//设置ringwidth的宽度的半圆环
canvas.drawArc(rectF, -90, 360 * mPercent, false, mPaint);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(dip2px(getContext(),15));
mPaint.setColor(Color.RED);
Paint.FontMetricsInt fontMetricsInt=mPaint.getFontMetricsInt();
canvas.drawText("100%",center-(fontMetricsInt.descent-fontMetricsInt.ascent)/2+fontMetricsInt.ascent/2,center+fontMetricsInt.bottom,mPaint);
super.onDraw(canvas);
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public void setmPercent(float mPercent
) {
this.mPercent = mPercent;
invalidate();
}
}
下一篇: Firefox63以后 禁止自动更新方式