一个简单的自定义View,仿圆形进度条

一个很简单的小例子,,整理一下

效果图

一个简单的自定义View,仿圆形进度条_第1张图片

上代码,代码中应该注释很清楚了,就不再赘述,是模仿洋大神写的,然后自己又加了一点儿自己的理解。

代码如下

package com.example.roundview;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

public class RoundView extends View {
	private int roundWidth;
	private int speed;//此处为自定义的速度,简单点,speed是几,几秒转完一圈
	private Paint mPaint;
	private int process;
	private int processColor = Color.BLUE;
	private RectF mRectf;
	private TextPaint textPaint;
	private Rect textRect;
	public RoundView(Context context) {
		this(context, null);
	}

	public RoundView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public RoundView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		setBackgroundColor(Color.YELLOW);
		initAttr(context, attrs);
		mPaint = new Paint();
		mRectf = new RectF();
		textRect = new Rect();
		textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
		textPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
		textPaint.setColor(Color.BLACK);
		textPaint.setStyle(Paint.Style.FILL);
		startRun();
	}
	//开始绘制
	private void startRun() {
		final int angle = 360/speed;
		new Thread(){
			public void run() {
				while(true){
					process+=angle;
					if(process == 360){
						process = 0;
						processColor = Color.GREEN;
					}
					postInvalidate();
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		}.start();
	}

	private void initAttr(Context context, AttributeSet attrs) {
		TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundView);
		roundWidth = array.getDimensionPixelSize(R.styleable.RoundView_roundWidth, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()));
		speed = array.getInt(R.styleable.RoundView_speed, 6);
		array.recycle();
	}
	

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
		
	}
	private int measureHeight(int heightMeasureSpec) {
		int height = 0;
		int minHeight = 154;//定义最小的高度为154,相当于layout_height为wrap_content的时候,高度为154px
		int specMode = MeasureSpec.getMode(heightMeasureSpec);
		int specSize = MeasureSpec.getSize(heightMeasureSpec);
		switch(specMode){
			case MeasureSpec.EXACTLY:
				height = specSize

你可能感兴趣的:(android)