Android自定义没有资源文件的圆形进度条ProgressBar

     最近公司开发的SDK中需要使用圆形加载进度条,而且说要那种动态的转圈圈的那种进度条。当然这种进度条想实现很简单,用几个资源图片,以动画循环播放就行。但考虑到是SDK,有资源文件不好打包,想打包就要用到资源映射什么的,太麻烦,干脆搞个简单的没有资源文件的~~


一、 进度条实现

     代码里面已经有解释,代码也非常简单,看看就明白。

package com.mobisummer.ads.wall;

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;

public class CircleProgressBar extends View {
	private static int START = -30;
	private static int SWEEP = 0;
	private static int FLAG = 1;
	private static final int DELAY = 100; // 延迟
	private int progressStrokeWidth; //进度环的厚度
	// 画圆所在的距形区域
	private RectF oval;
	private Paint paint;

	public CircleProgressBar(Context context, AttributeSet attrs, int stroke) {
		super(context, attrs);
		oval = new RectF();
		paint = new Paint();
		progressStrokeWidth = stroke;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		int width = this.getWidth();
		int height = this.getHeight();

		if (width != height) {
			int min = Math.min(width, height);
			width = min;
			height = min;
		}

		paint.setAntiAlias(true); // 设置画笔为抗锯齿
		paint.setColor(Color.WHITE); // 设置画笔颜色
		canvas.drawColor(Color.TRANSPARENT); // 白色背景
//		int progressStrokeWidth = 10;
		paint.setStrokeWidth(progressStrokeWidth); // 线宽
		paint.setStyle(Paint.Style.STROKE);

		oval.left = progressStrokeWidth / 2; // 矩形的左边位置。
		oval.top = progressStrokeWidth / 2; // 矩形的上边位置。
		oval.right = width - progressStrokeWidth / 2; // 矩形的右边位置。
		oval.bottom = height - progressStrokeWidth / 2; // 矩形的下边位置。

		canvas.drawArc(oval, -90, 360, false, paint); // 绘制白色圆圈,即进度条背景
		
		paint.setColor(Color.rgb(34, 139, 34)); //设置圆进度条的颜色
		//计算进度圆弧的弧度
		START += 30;
		if (START > 360) {
			START -= 360;
		}
		if (SWEEP > 270) {
			FLAG = -1;
		} else if (SWEEP < 60) {
			FLAG = 1;
		}
		SWEEP += 20*FLAG;
		canvas.drawArc(oval, START, SWEEP, false, paint); // 绘制进度圆弧
		getHandler().postDelayed(runnable, DELAY); //循环刷新
	}

	// 重绘线程
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// 自动刷新
			invalidate();
		}
	};

}



二、 进度条的使用

		Resources res = getResources();
		// 添加进度 条
		mProgressbar = new CircleProgressBar(mActivity, null, (int)res.getDimension(R.dimen.circle_progressbar_stroke));
		//屏幕宽高
		mWidth = DimensionUtil.getDisplayWidth(mActivity);
		mHeight = DimensionUtil.getDisplayHeight(mActivity);
		DebugUtil.d(TAG, "mWidth : " + mWidth + ", mHeight : " + mHeight);
		//获取进度条半径大小
		int size = (int) res.getDimension(R.dimen.circle_progressbar_radius);
		DebugUtil.d(TAG, "size : " + size );
		mProgressbar.setLayoutParams(new LayoutParams(size, size,
				(mWidth - size) / 2, (mHeight - size) / 2));
		addView(mProgressbar);



你可能感兴趣的:(Android基础)